之前我们的工具类没有事务提交,我们就需要在测试的时候人工判断是不是增删改(查询不需要添加事务),为了简化,我们这次将事务提交写在工具类中
package com.muan.utils;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import java.io.IOException;
import java.io.InputStream;
public class MyBatisUtils {
private static SqlSession sqlSession;
static {
try {
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
//openSession方法的自动提交设置为true就会自动提交了
sqlSession= sqlSessionFactory.openSession(true);
} catch (IOException e) {
e.printStackTrace();
}
}
public static SqlSession getSqlSession(){
return sqlSession;
}
}
创建Maven项目,配置pom.xml,配置Maven依赖导包
4.0.0
com.muan
MyBatis练习
1.0-SNAPSHOT
junit
junit
4.11
org.mybatis
mybatis
3.5.1
mysql
mysql-connector-java
5.1.47
log4j
log4j
1.2.17
src/main/java
**/*.properties
**/*.xml
false
src/main/resources
**/*.properties
**/*.xml
false
编写pojo
package com.muan.pojo;
public class User {
private int id;
private String name;
private String pwd;
public User() {
}
public User(int id, String name, String pwd) {
this.id = id;
this.name = name;
this.pwd = pwd;
}
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 String getPwd() {
return pwd;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", name='" + name + '\'' +
", pwd='" + pwd + '\'' +
'}';
}
}
使用注解开发,我们就不需要再写接口的映射文件userMapper.xml了,可以直接在接口的方法上使用一个注解,在注解的参数里书写SQL语句
UserMapper接口
package com.muan.dao;
import com.muan.pojo.User;
import org.apache.ibatis.annotations.*;
import java.util.List;
public interface UserMapper {
//查询全部用户
@Select("select * from user")
List getUserList();
//通过ID查询用户
@Select("select * from user where id = #{id}")
User getUserById(@Param("id") int id);
//添加用户
@Insert("insert into user(id,name,pwd) values (#{id},#{name},#{pwd})")
int addUser(User user);
//修改用户信息
@Update("update user set name = #{name}, pwd = #{pwd} where id = #{id}")
int updateUser(User user);
//删除用户
@Delete("delete from user where id =#{uid}")
int deleteUser(@Param("uid") int id);
}
database.properties
driver = com.mysql.jdbc.Driver
username = root
password = 123456
url = jdbc:mysql://localhost:3306/mybatis?useSSL=true&useUnicode=true&characterEncoding=UTF-8
log4j.properties
### Log4j配置 ###
### 与Spring结合需要在web.xml中指定此文件位置,并添加监听器 ###
#定义log4j的输出级别和输出目的地(目的地可以自定义名称,和后面的对应)
#[ level ] , appenderName1 , appenderName2
log4j.rootLogger=DEBUG,console,file
#-----------------------------------#
#1 定义日志输出目的地为控制台
log4j.appender.console = org.apache.log4j.ConsoleAppender
log4j.appender.console.Target = System.out
log4j.appender.console.Threshold=DEBUG
####可以灵活地指定日志输出格式,下面一行是指定具体的格式 ###
#%c: 输出日志信息所属的类目,通常就是所在类的全名
#%m: 输出代码中指定的消息,产生的日志具体信息
#%n: 输出一个回车换行符,Windows平台为"/r/n",Unix平台为"/n"输出日志信息换行
log4j.appender.console.layout = org.apache.log4j.PatternLayout
log4j.appender.console.layout.ConversionPattern=[%c]-%m%n
#-----------------------------------#
#2 文件大小到达指定尺寸的时候产生一个新的文件
log4j.appender.file = org.apache.log4j.RollingFileAppender
#日志文件输出目录
log4j.appender.file.File=log/tibet.log
#定义文件最大大小
log4j.appender.file.MaxFileSize=10mb
###输出日志信息###
#最低级别
log4j.appender.file.Threshold=ERROR
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=[%p][%d{yy-MM-dd}][%c]%m%n
#-----------------------------------#
#3 druid
log4j.logger.druid.sql=INFO
log4j.logger.druid.sql.DataSource=info
log4j.logger.druid.sql.Connection=info
log4j.logger.druid.sql.Statement=info
log4j.logger.druid.sql.ResultSet=info
#4 mybatis 显示SQL语句部分
log4j.logger.org.mybatis=DEBUG
#log4j.logger.cn.tibet.cas.dao=DEBUG
#log4j.logger.org.mybatis.common.jdbc.SimpleDataSource=DEBUG
#log4j.logger.org.mybatis.common.jdbc.ScriptRunner=DEBUG
#log4j.logger.org.mybatis.sqlmap.engine.impl.SqlMapClientDelegate=DEBUG
#log4j.logger.java.sql.Connection=DEBUG
log4j.logger.java.sql=DEBUG
log4j.logger.java.sql.Statement=DEBUG
log4j.logger.java.sql.ResultSet=DEBUG
log4j.logger.java.sql.PreparedStatement=DEBUG
配置mybatis-config.xml
测试:
import com.muan.dao.UserMapper;
import com.muan.pojo.User;
import com.muan.utils.MyBatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
import java.util.HashMap;
import java.util.List;
public class UserMapperTest {
//这里注意,我们已经优化了工具类,增删改方法就不用在这里提交事务了,但是要注意关闭事务
//获取全部用户
@Test
public void getUserList(){
SqlSession sqlSession = MyBatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
List userList = mapper.getUserList();
for (User user : userList) {
System.out.println(user);
}
sqlSession.close();
}
//通过ID查询用户
@Test
public void getUserById(){
SqlSession sqlSession = MyBatisUtils.getSqlSession();//带自动提交事务
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
User user = mapper.getUserById(1);
System.out.println(user);
sqlSession.close();//关闭sqlSession;
}
//添加用户
@Test
public void addUser(){
SqlSession sqlSession = MyBatisUtils.getSqlSession();//带自动提交事务
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
User user = new User(4, "阿猫", "like-dog");
int i = mapper.addUser(user);
System.out.println(i);
sqlSession.close();//关闭sqlSession;
}
//修改用户信息
@Test
public void updateUser(){
SqlSession sqlSession = MyBatisUtils.getSqlSession();//带自动提交事务
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
User user = new User(4, "阿狗", "999999");
int i = mapper.updateUser(user);
System.out.println(i);
sqlSession.close();//关闭sqlSession;
}
//删除用户
@Test
public void deleteUser(){
SqlSession sqlSession = MyBatisUtils.getSqlSession();//带自动提交事务
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
int i = mapper.deleteUser(4);
System.out.println(i);
sqlSession.close();//关闭sqlSession;
}
}