一、前言
Mybatis和Maven配置起来其实挺麻烦的,很容易忘记,所以记录一下配置的过程。Mybatis作为一个持久层的框架,是用来和数据库打交道的。这里以MySQL数据库为例,对用户user表进行增删改查。
二、 步骤
- 新建一个Maven工程,可以不用骨架。
- 先配置一下Maven工程的pom.xml,相当与传统的“导入jar包”,代码如下:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>cug</groupId>
<artifactId>MybatisCRUD</artifactId>
<version>1.0-SNAPSHOT</version>
<!--我是分界线,上面的内容是自动生成的,下面的才是手动增加的-->
<packaging>jar</packaging>
<dependencies>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.5</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.26</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
</dependencies>
</project>
- 给学生表写一个实体类,学生表如下图:
实体类的代码如下:
package domain;
import java.util.Date;
/**
* @author laoyingyong
* @date: 2019-12-26 19:29
*/
public class User
{
private Integer id;
private String username;
private Date birthday;
private String sex;
private String address;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", username='" + username + '\'' +
", birthday=" + birthday +
", sex='" + sex + '\'' +
", address='" + address + '\'' +
'}';
}
}
- 写一个UserDao接口,代码如下:
package dao;
import domain.User;
import java.util.List;
/**
* @author laoyingyong
* @date: 2019-12-26 19:42
*/
public interface UserDao {
/**
* 查询所有用户
* @return
*/
List<User> findAll();
/**
* 保存方法
* @param user
*/
void saveUser(User user);
/**
* 更新方法
* @param user
*/
void updateUser(User user);
/**
* 删除方法
* @param userId
*/
void deleteUser(Integer userId);
}
- 新建一个Mybatis的配置文件SqlMapCofig.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="mysql">
<environment id="mysql">
<transactionManager type="JDBC"></transactionManager>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"></property>
<property name="url" value="jdbc:mysql://localhost:3306/test?characterEncoding=utf8"></property>
<property name="username" value="root"></property>
<property name="password" value=""></property>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="dao/UserDao.xml"></mapper>
</mappers>
</configuration>
- 新建一个映射配置文件UserDao.xml,注意UserDao.xml
存放的位置,要放在dao目录下,和接口的一样。整个项目的结构如下图所示:
UserDao.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="dao.UserDao">
<select id="findAll" resultType="domain.User">
select * from user;
</select>
<insert id="saveUser" parameterType="domain.User">
insert into user (username,birthday,sex,address)values(#{username},#{birthday},#{sex},#{address});
</insert>
<update id="updateUser" parameterType="domain.User">
update user set username=#{username},birthday=#{birthday},sex=#{sex},address=#{address} where id=#{id};
</update>
<delete id="deleteUser" parameterType="java.lang.Integer">
delete from user where id=#{uid};/*uid只是占位符*/
</delete>
</mapper>
- 因为用到了单元测试,测试类的代码如下:
package test;
import dao.UserDao;
import domain.User;
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 org.junit.Test;
import java.io.InputStream;
import java.util.Date;
import java.util.List;
/**
* @author laoyingyong
* @date: 2019-12-26 19:49
*/
public class MybatisTest {
@Test
public void testFindAll() throws Exception
{
InputStream in = Resources.getResourceAsStream("SqlMapConfig.xml");
SqlSessionFactory factory=new SqlSessionFactoryBuilder().build(in);
SqlSession sqlSession = factory.openSession();
UserDao userDao = sqlSession.getMapper(UserDao.class);
List<User> list = userDao.findAll();
for (User user : list) {
System.out.println(user);
}
sqlSession.close();
in.close();
}
@Test
public void testSaveUser() throws Exception
{
User user=new User();
user.setUsername("鲁班");
user.setBirthday(new Date());
user.setAddress("峡谷");
user.setSex("男");
InputStream in = Resources.getResourceAsStream("SqlMapConfig.xml");
SqlSessionFactory factory=new SqlSessionFactoryBuilder().build(in);
SqlSession sqlSession = factory.openSession();
UserDao userDao = sqlSession.getMapper(UserDao.class);
userDao.saveUser(user);
sqlSession.commit();
sqlSession.close();
in.close();
}
@Test
public void testUpdateUser() throws Exception
{
User user=new User();
user.setId(50);
user.setUsername("小鲁班");
user.setBirthday(new Date());
user.setAddress("王者峡谷");
user.setSex("男");
InputStream in = Resources.getResourceAsStream("SqlMapConfig.xml");
SqlSessionFactory factory=new SqlSessionFactoryBuilder().build(in);
SqlSession sqlSession = factory.openSession();
UserDao userDao = sqlSession.getMapper(UserDao.class);
userDao.updateUser(user);
sqlSession.commit();
sqlSession.close();
in.close();
}
@Test
public void testDeleteUser() throws Exception
{
InputStream in = Resources.getResourceAsStream("SqlMapConfig.xml");
SqlSessionFactory factory=new SqlSessionFactoryBuilder().build(in);
SqlSession sqlSession = factory.openSession();
UserDao userDao = sqlSession.getMapper(UserDao.class);
userDao.deleteUser(50);
sqlSession.commit();
sqlSession.close();
in.close();
}
}
- 再给出日志log4j的配置log4j.properties,代码如下:
# Set root category priority to INFO and its only appender to CONSOLE.
#log4j.rootCategory=INFO, CONSOLE debug info warn error fatal
log4j.rootCategory=debug, CONSOLE, LOGFILE
# Set the enterprise logger category to FATAL and its only appender to CONSOLE.
log4j.logger.org.apache.axis.enterprise=FATAL, CONSOLE
# CONSOLE is set to be a ConsoleAppender using a PatternLayout.
log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
log4j.appender.CONSOLE.layout.ConversionPattern=%d{ISO8601} %-6r [%15.15t] %-5p %30.30c %x - %m\n
# LOGFILE is set to be a File appender using a PatternLayout.
log4j.appender.LOGFILE=org.apache.log4j.FileAppender
log4j.appender.LOGFILE.File=d:\axis.log
log4j.appender.LOGFILE.Append=true
log4j.appender.LOGFILE.layout=org.apache.log4j.PatternLayout
log4j.appender.LOGFILE.layout.ConversionPattern=%d{ISO8601} %-6r [%15.15t] %-5p %30.30c %x - %m\n
三、总结
- 当然最后的单元测试有很多代码都是重复的,为了省事我也就没有进行共性代码的抽取,直接复制粘贴,更加节省时间。
- 其实UserDao.xml这个配置文件也有替代者,就是使用注解的方式去配置,这里就不说明如何使用注解配置了。
- 与之前学的JdbcTemplate相比,采用Mybatis框架可以少写很多的逻辑代码,缺点就是入门者很不适应xml配置,感觉比较麻烦,难以记住配置的流程和一些细节方面的东西。(JdbcTemplate不能说是框架,它只是Spring框架下的一个工具类)
- 最好让实体类的属性名和数据库中的列名保持一致,否则会引起不必要的麻烦。(虽说实体类的属性名和数据库表中的列名不可以不相同,但配置xml时会很麻烦,要多写很多东西)。
- 上面的UserDao接口我并没有写对应的实现类,但Mybatis同样也支持写Dao的实现类,但是最好不写,因为增加了很多代码。使用框架就是为了简化开发,还写实现类的话,也是自找麻烦。