mybatis学习笔记(二)-- 使用mybatisUtil工具类体验基于xml和注解实现

时间:2021-08-05 21:40:33
  • 项目结构

mybatis学习笔记(二)-- 使用mybatisUtil工具类体验基于xml和注解实现

   基础入门可参考:mybatis学习笔记(一)-- 简单入门(附测试Demo详细过程)

  • 开始体验

  1、新建项目,新建类MybatisUtil.java,路径:src/util/MybatisUtil.java

package util;

import java.io.InputStream;

import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder; public class MybatisUtil { /**
* 获取SqlSessionFactory
* @return SqlSessionFactory
*/
public static SqlSessionFactory getSqlSessionFactory() {
String resource = "conf.xml";
InputStream is = MybatisUtil.class.getClassLoader().getResourceAsStream(resource);
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(is);
return factory;
} /**
* 获取SqlSession
* @return SqlSession
*/
public static SqlSession getSqlSession() {
return getSqlSessionFactory().openSession();
} /**
* 获取SqlSession
* @param isAutoCommit
* true 表示创建的SqlSession对象在执行完SQL之后会自动提交事务
* false 表示创建的SqlSession对象在执行完SQL之后不会自动提交事务,这时就需要我们手动调用sqlSession.commit()提交事务
* @return SqlSession
*/
public static SqlSession getSqlSession(boolean isAutoCommit) {
return getSqlSessionFactory().openSession(isAutoCommit);
}
}

  2、编写用户实体类User.java,路径:src/main/User.java

package main;

public class User {

    private int id;
private String name;
private int age; public int getId() {
return id;
} public void setId(int id) {
this.id = id;
} public String getName() {
return name;
} public void setName(String name) {
this.name = name;
} public int getAge() {
return age;
} public void setAge(int age) {
this.age = age;
}
}

  3、编写mapper,以“新增用户”为示范案例

  mybatis学习笔记(二)-- 使用mybatisUtil工具类体验基于xml和注解实现

  (1)基于xml实现,定义操作用户表的sql映射文件UserMapper.xml,路径:src/mapper/UserMapper.xml

<?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="mapper.UserMapper"> <!-- 新增用户 -->
<insert id="addUser" parameterType="main.User">
insert into tb_user(name,age) values(#{name},#{age})
</insert> </mapper>

  (2)基于注解实现,定义sql映射的接口,使用注解指明方法要执行的SQL,新建UserMapperI.java,路径:src/mapper/UserMapperI.java

package mapper;

import java.util.List;
import main.User;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update; public interface UserMapperI { //使用@Insert注解指明add方法要执行的SQL
@Insert("insert into tb_user(name, age) values(#{name}, #{age})")
public int add(User user); }

  4、添加配置文件,新建conf.xml文件,路径:src/conf.xml

<?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/test" />
<property name="username" value="root" />
<property name="password" value="123456" />
</dataSource>
</environment>
</environments> <mappers>
<!-- 注册userMapper.xml文件(基于xml实现)-->
<mapper resource="mapper/userMapper.xml"/>
<!-- 注册UserMapper映射接口(基于注解实现)-->
<mapper class="mapper.UserMapperI"/>
</mappers> </configuration>

5、编写测试函数

(1)测试基于xml实现

public static void testAddByXmlMapper(){
//SqlSession sqlSession = MyBatisUtil.getSqlSession(false);
SqlSession sqlSession = MybatisUtil.getSqlSession(true);
String statement = "mapper.UserMapper.addUser";//映射sql的标识字符串
User user = new User();
user.setName("lucy");
user.setAge(22);
//执行插入操作
int retResult = sqlSession.insert(statement,user);
//手动提交事务
//sqlSession.commit();
//使用SqlSession执行完SQL之后需要关闭SqlSession
sqlSession.close();
System.out.println(retResult);
}
 * 注解:

  SqlSession sqlSession = MybatisUtil.getSqlSession(true);

  true 表示创建的SqlSession对象在执行完SQL之后会自动提交事务

  false 表示创建的SqlSession对象在执行完SQL之后不会自动提交事务,这时就需要我们手动调用sqlSession.commit()提交事务

(2)测试基于注解实现

public void testAddByAnnotationMapper() {
SqlSession sqlSession = MybatisUtil.getSqlSession(true);
// 得到UserMapperI接口的实现类对象,UserMapperI接口的实现类对象由sqlSession.getMapper(UserMapperI.class)动态构建出来
UserMapperI mapper = sqlSession.getMapper(UserMapperI.class);
User user = new User();
user.setName("tom");
user.setAge(20);
int add = mapper.add(user);
// 使用SqlSession执行完SQL之后需要关闭SqlSession
sqlSession.close();
System.out.println(add);
}

  

  到此结束~ (@_@)以上...