Mybatis 原始dao CRUD方法
用到的相关jar包及所用版本如下:
其中的Mybatis可以到github.com的网站下载
<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>com.swift</groupId> <artifactId>mybatis02</artifactId> <version>0.0.1-SNAPSHOT</version> <dependencies> <!-- junit --> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>test</scope> </dependency> <!-- mybatis --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.2.7</version> </dependency> <!-- mysql驱动 --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.46</version> </dependency> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.17</version> </dependency> </dependencies> </project>
使用mysql数据库进行测试
为了方便修改数据库参数,使用了db.properties
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mybatis?characterEncoding=utf-8
jdbc.username=root
jdbc.password=root
在Mybatis的配置文件中加载这个properties
SqlMapConfig.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> <!-- 外部引入的配置信息优先级高于子标签定义的配置信息 --> <properties resource="db.properties"> <!-- <property name="jdbc.username" value="root" /> --> </properties> <environments default="development"> <!-- 开发用数据源 --> <environment id="development"> <transactionManager type="JDBC" /> <dataSource type="POOLED"> <property name="driver" value="${jdbc.driver}" /> <property name="url" value="${jdbc.url}" /> <property name="username" value="${jdbc.username}" /> <property name="password" value="${jdbc.password}" /> </dataSource> </environment> </environments> <!-- 加载sql映射文件 --> <mappers> <mapper resource="sqlmap/UserMapper.xml" /> </mappers> </configuration>
此时项目的结构如下
与Hibernate的纯orm映射(把实体映射成数据库表,并且表与表的关系也映射了,基本上完全封装了sql)不同,
Mybatis的映射文件是要自己写SQL的,而不是由Hibernate自动生成
纯洁的pojo实体类
package com.swift.pojo; import java.io.Serializable; import java.util.Date; public class User implements Serializable { private static final long serialVersionUID = 1L; private String uid; private String username; private String password; private String name; private String email; private String telephone; private Date birthday; private String gender; private int state; private String code; public Date getBirthday() { return birthday; } public void setBirthday(Date birthday) { this.birthday = birthday; } public String getUid() { return this.uid; } public void setUid(String uid) { this.uid = uid; } public String getUsername() { return this.username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return this.password; } public void setPassword(String password) { this.password = password; } public String getName() { return this.name; } public void setName(String name) { this.name = name; } public String getEmail() { return this.email; } public void setEmail(String email) { this.email = email; } public String getTelephone() { return this.telephone; } public void setTelephone(String telephone) { this.telephone = telephone; } public int getState() { return this.state; } public void setState(int state) { this.state = state; } public String getCode() { return this.code; } public void setCode(String code) { this.code = code; } public String getGender() { return this.gender; } public void setGender(String gender) { this.gender = gender; } @Override public String toString() { return "User [uid=" + uid + ", username=" + username + ", password=" + password + ", name=" + name + ", email=" + email + ", telephone=" + telephone + ", birthday=" + birthday + ", gender=" + gender + ", state=" + state + ", code=" + code + "]"; } }
Mybatis 的sql映射文件 只是写了SQL语言的CRUD
通过这个映射UserMapper.xml文件 可以对User这个pojo类进行相关操作
<?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="test"> <!-- resultType:返回多条记录时配置和单条一样,mybatis会自动把多条数据放到集合里面 --> <select id="queryUserByUsername" parameterType="String" resultType="com.swift.pojo.User"> select * from user where username = #{username} </select> <select id="queryUserByTelephone" parameterType="String" resultType="com.swift.pojo.User"> select * from user where telephone like #{telephone} </select> <select id="queryUserByTelephone2" parameterType="String" resultType="com.swift.pojo.User"> select * from user where telephone like '%${value}%' </select> <insert id="saveUser" parameterType="com.swift.pojo.User"> INSERT INTO USER(uid,username,password,name) VALUES(#{uid},#{username},#{password},#{name}) </insert> <update id="updateUserById" parameterType="com.swift.pojo.User"> UPDATE USER SET birthday = #{birthday} WHERE uid = #{uid} </update> </mapper>
那么如何调用这个映射文件中的crud sql配置呢?Mybatis原始的dao的方法需要我们建立pojo的dao接口和实现类,来调用映射文件中sql配置
Dao接口 UserDao.java
package com.swift.dao; import java.util.List; import com.swift.pojo.User; public interface UserDao { User queryUserByUsername(String username); List<User> queryUserByTelephone(String telephone); List<User> queryUserByTelephone2(String telephone); void saveUser(User user); void updateUserById(User user); }
实体类
package com.swift.dao; import java.util.List; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import com.swift.pojo.User; public class UserDaoImpl implements UserDao { private SqlSessionFactory sqlSessionFactory; public UserDaoImpl(SqlSessionFactory sqlSessionFactory) { this.sqlSessionFactory = sqlSessionFactory; } public User queryUserByUsername(String username) { SqlSession sqlSession = sqlSessionFactory.openSession(); User user = sqlSession.selectOne("test.queryUserByUsername", username); sqlSession.close(); return user; } public List<User> queryUserByTelephone(String telephone) { SqlSession sqlSession = sqlSessionFactory.openSession(); List<User> users = sqlSession.selectList("test.queryUserByTelephone", telephone); sqlSession.close(); return users; } public List<User> queryUserByTelephone2(String telephone) { SqlSession sqlSession = sqlSessionFactory.openSession(); List<User> users = sqlSession.selectList("test.queryUserByTelephone2", telephone); sqlSession.close(); return users; } public void saveUser(User user) { SqlSession sqlSession = sqlSessionFactory.openSession(); sqlSession.selectOne("test.saveUser", user); sqlSession.close(); } public void updateUserById(User user) { SqlSession sqlSession = sqlSessionFactory.openSession(); sqlSession.selectOne("test.updateUserById", user); sqlSession.close(); } }
测试类
package com.swift.test; import java.io.IOException; import java.io.InputStream; import java.util.List; import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; import org.junit.Test; import com.swift.dao.UserDao; import com.swift.dao.UserDaoImpl; import com.swift.pojo.User; public class UserDaoTest { private SqlSessionFactory sqlSessionFactory; @Test public void testQueryUserById() throws IOException { // 创建SqlSessionFactoryBuilder SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder(); // 加载SqlMapConfig.xml配置文件 InputStream inputStream = Resources.getResourceAsStream("SqlMapConfig.xml"); // 创建SqlsessionFactory this.sqlSessionFactory = sqlSessionFactoryBuilder.build(inputStream); // 创建DAO UserDao userDao = new UserDaoImpl(this.sqlSessionFactory); // 执行查询 User user = userDao.queryUserByUsername("swift"); System.out.println(user); } @Test public void testQueryUserByTelephone() throws IOException { // 创建SqlSessionFactoryBuilder SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder(); // 加载SqlMapConfig.xml配置文件 InputStream inputStream = Resources.getResourceAsStream("SqlMapConfig.xml"); // 创建SqlsessionFactory this.sqlSessionFactory = sqlSessionFactoryBuilder.build(inputStream); // 创建DAO UserDao userDao = new UserDaoImpl(this.sqlSessionFactory); // 执行查询 List<User> users = userDao.queryUserByTelephone("%186%"); for (User user : users) { System.out.println(user); } } }
为了能看到结果
还要有个log日志文件log4j.properties
# Global logging configuration log4j.rootLogger=DEBUG, stdout # Console output... log4j.appender.stdout=org.apache.log4j.ConsoleAppender log4j.appender.stdout.layout=org.apache.log4j.PatternLayout log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n