Mybatis, mybatis

Source: Internet
Author: User

Mybatis, mybatis

1. Introduction to MyBatis

MyBatis is an excellent persistent layer framework that supports common SQL queries, stored procedures, and advanced mappings. MyBatis eliminates the manual setup of almost all JDBC code and parameters and retrieval encapsulation of result sets. MyBatis can use simple XML or annotations for configuration and original ing. It maps interfaces and Java POJO (Plain Old Java Objects, common Java Objects) into records in the database.


Mybatis-3.1.1: http://download.csdn.net/detail/huhui_bj/8575253


Ii. Quick Start

2.1 preparation

First you need to add two jar packages, one is the mybatis-3.1.1.jar, the other is the mysql-connector-java-5.1.7-bin.jar. Create a database and a data table in MySQL:

create database mybatis;use mybatis;CREATE TABLE users(id INT PRIMARY KEY AUTO_INCREMENT, NAME VARCHAR(20), age INT);INSERT INTO users(NAME, age) VALUES('Tom', 12);INSERT INTO users(NAME, age) VALUES('Jack', 11);

2.2 Add the configuration file conf. xml for Mybatis

<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"><configuration><environments default="development"><environment id="development"><transactionManager type="JDBC" /><dataSource type="POOLED"><property name="driver" value="com.mysql.jdbc.Driver" /><property name="url" value="jdbc:mysql://localhost:3306/mybatis" /><property name="username" value="root" /><property name="password" value="root" /></dataSource></environment></environments></configuration>

2.3 define the object class corresponding to the table

Public class User {private int id; private String name; private int age; // get, set Method}

2.4 define the SQL ing file userMapper. xml for operating the users table

<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.atguigu.mybatis_test.test1.userMapper"> <select id="getUser" parameterType="int" resultType="com.atguigu.mybatis_test.test1.User">select * from users where id=#{id}</select></mapper>

2.5 register userMapper. xml in the conf. xml file

<mappers><mapper resource="com/atguigu/mybatis_test/test1/userMapper.xml"/></mappers>

2.6 write test code

String resource = "conf. xml "; // load the configuration file of mybatis (It also loads the associated ing file) Reader reader = Resources. getResourceAsReader (resource); // The SqlSessionFactory sessionFactory that constructs the sqlSession = new SqlSessionFactoryBuilder (). build (reader); // create sqlSessionSqlSession session = sessionFactory that can execute SQL IN THE ing file. openSession (); // String statement = "com. atguigu. mybatis. bean. userMapper "+ ". selectUser "; // run the query to return the sqlUser user = session of a unique user object. selectOne (statement, 1); System. out. println (user );

Iii. Data Table CRUD operations

3.1 XML implementation

<insert id="insertUser" parameterType="com.atguigu.ibatis.bean.User">insert into users(name, age) values(#{name}, #{age});</insert><delete id="deleteUser" parameterType="int">delete from users where id=#{id}</delete><update id="updateUser" parameterType="com.atguigu.ibatis.bean.User">update users set name=#{name},age=#{age} where id=#{id}</update><select id="selectUser" parameterType="int" resultType="com.atguigu.ibatis.bean.User">select * from users where id=#{id}</select><select id="selectAllUsers" resultType="com.atguigu.ibatis.bean.User">select * from users</select>

3.2 Implementation of annotations

public interface UserMapper {@Insert("insert into users(name, age) values(#{name}, #{age})")public int insertUser(User user);@Delete("delete from users where id=#{id}")public int deleteUserById(int id);@Update("update users set name=#{name},age=#{age} where id=#{id}")public int updateUser(User user);@Select("select * from users where id=#{id}")public User getUserById(int id);@Select("select * from users")public List<User> getAllUser();}

Register the ing interface in conf. xml:

<mapper class="com.atguigu.ibatis.crud.ano.UserMapper"/>

Call in DAO class:

public User getUserById(int id) {SqlSession session = sessionFactory.openSession();UserMapper mapper = session.getMapper(UserMapper.class);User user = mapper.getUserById(id);return user;}

4. Several Optimizations

4.1 create a database configuration file

## db.properties<properties resource="db.properties"/><property name="driver" value="${driver}" /><property name="url" value="${url}" /><property name="username" value="${username}" /><property name="password" value="${password}" />

Then add the configuration for reading db. properties to the configuration file conf. xml of Mybatis:

<! -- Introduce the resource file --> <properties resource = "db. properties"/>

4.2 define aliases for object classes

<! -- Configure the object class alias --> <typeAliases> <! -- <TypeAlias type = "com. mybatis. test1.User" alias = "_ User"/> --> <package name = "com. mybatis. bean"/> <! -- Scan this package --> </typeAliases>
The above configuration can simplify the reference in the SQL ing xml file, and you do not need to write the full path of the class every time.


4.3 Add a log4j configuration file to print log information

#log4j.propertieslog4j.rootLogger=DEBUG, Console#Consolelog4j.appender.Console=org.apache.log4j.ConsoleAppenderlog4j.appender.Console.layout=org.apache.log4j.PatternLayoutlog4j.appender.Console.layout.ConversionPattern=%d [%t] %-5p [%c] - %m%nlog4j.logger.java.sql.ResultSet=INFOlog4j.logger.org.apache=INFOlog4j.logger.java.sql.Connection=DEBUGlog4j.logger.java.sql.Statement=DEBUGlog4j.logger.java.sql.PreparedStatement=DEBUG



Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.