<?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>com.thinkcoder</groupId>
<artifactId>mybatis的CRUD操作</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<!--mybatis的依赖-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.5</version>
</dependency>
<!--mysql的依赖-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.6</version>
</dependency>
<!--日志依赖-->
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j</artifactId>
<version>2.12.1</version>
</dependency>
<!--单元测试依赖-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>RELEASE</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>
public interface IUserDao {
//查询所有用户
List<User> findAll();
// 增删改查的方法写到这里
}
为了看的清晰(好吧,我偷懒,哈哈哈),剩下的crud的操作,只写当前的操作,就不带之前的方法了
建表的sql脚本
CREATE TABLE `user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(32) NOT NULL COMMENT '用户名称',
`birthday` datetime DEFAULT NULL COMMENT '生日',
`sex` char(1) DEFAULT NULL COMMENT '性别',
`address` varchar(256) DEFAULT NULL COMMENT '地址',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=49 DEFAULT CHARSET=utf8;
User类
package com.thinkcoder.domain;
import java.io.Serializable;
import java.util.Date;
/**
* @ClassName User
* @Author ThinkCocer
*/
public class User implements Serializable {
private Integer id;
private String username;
private Date birthday;
private String sex;
private String address;
//getter和setter方法
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}
//重写tostring方法
@Override
public String toString() {
return "User{" +
"id=" + id +
", username='" + username + '\'' +
", birthday=" + birthday +
", sex='" + sex + '\'' +
", address='" + address + '\'' +
'}';
}
}
IUserDao.xml映射配置文件
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.thinkcoder.dao.IUserDao">
<!--查询所有-->
<select id="findAll" resultType="com.thinkcoder.domain.User">
select * from user;
</select>
</mapper>
要求:因为实现基于Dao代理对象实现,所以没有IUserDao接口的实现类,要符合以下要求
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>
<!--配置环境-->
<environments default="mysql">
<!--配置mysql的环境-->
<environment id="mysql">
<!--配置事务-->
<transactionManager type="JDBC"></transactionManager>
<!--配置连接池-->
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/selfproj?useUnicode=true&characterEncoding=utf8"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</dataSource>
</environment>
</environments>
<!--配置映射文件的位置-->
<mappers>
<mapper resource="com/thinkcoder/dao/IUserDao.xml"></mapper>
</mappers>
</configuration>
MybatisTest类
/**
* @ClassName MybatisTest
* @Author ThinkCoder
* 测试mybatis的crud操作
*/
public class MybatisTest {
private InputStream in;
private SqlSessionFactory factory;
private SqlSession session;
private IUserDao userDao;
@Before //用于测试方法执行之前执行
public void init()throws Exception{
//1.读取配置文件,生成字节输入流
in = Resources.getResourceAsStream("SqlMapConfig.xml");
//2.获取SqlSessionFactory
factory = new SqlSessionFactoryBuilder().build(in);
//3.获取sqlsession对象
session = factory.openSession();
//4.获取dao的代理对象
userDao = session.getMapper(IUserDao.class);
}
@After //用于测试之后执行
public void realese()throws Exception{
session.close();
in.close();
}
@Test //测试查询所有方法
public void testFindAll() throws Exception {
//调用方法初始化
init();
//执行查询所有方法
List<User> userList = userDao.findAll();
for(User user:userList){
System.out.println(user);
}
//调用方法释放资源
realese();
}
}
上述代码完成了开发环境搭建并实现了测试查询所有用户的信息的操作,环境搭建完后
完成crud其他操作,只需要在下面三个文件中写代码
IUserDao接口
public interface IUserDao{
//添加用户
int insertUser(User user)
}
IUserDao.xml文件
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.thinkcoder.dao.IUserDao">
<!--添加用户-->
<insert id="insertUser" parameterType="com.thinkcoder.domain.User">
insert into user(username,birthday,sex,address) values (#{username},#{birthday},#{sex},#{address});
</insert>
</mapper>
MybatisTest类
public class MybatisTest {
private InputStream in;
private SqlSessionFactory factory;
private SqlSession session;
private IUserDao userDao;
@Test//测试添加用户的方法
public void testInsert() throws Exception{
User user = new User();
user.setUsername("渣男");
user.setBirthday(new Date());
user.setSex("男");
user.setAddress("天堂");
int res = userDao.insertUser(user);
System.out.Println(res);//1
//提交事务
session.commit();
}
//以下两个方法分别在测试方法自动前后执行
@Before //用于测试方法执行之前执行
public void init()throws Exception{
//1.读取配置文件,生成字节输入流
in = Resources.getResourceAsStream("SqlMapConfig.xml");
//2.获取SqlSessionFactory
factory = new SqlSessionFactoryBuilder().build(in);
//3.获取sqlsession对象
session = factory.openSession();
//4.获取dao的代理对象
userDao = session.getMapper(IUserDao.class);
}
@After //用于测试之后执行
public void realese()throws Exception{
session.close();
in.close();
}
}
说明
IUserDao接口
public interface IUserDao{
//修改用户
int updateUser(User user);
}
IUserDao.xml
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.thinkcoder.dao.IUserDao">
<!--修改用户-->
<update id="updateUser" parameterType="com.thinkcoder.domain.User">
update user set username = #{username} where id=#{id}
</update>
</mapper>
MybatisTest类
public class MybatisTest {
//测试方法如上就省略了
@Test
public void testUpdate(){
User user = new User();
user.setUsername("天线宝宝");
user.setId(49);
int res = userDao.updateUser(user);
//提交事务
session.commit();
System.out.println(res);
}
}
IUserDao接口
public interface IUserDao {
//删除用户
int deleteUser(Integer userId);
}
IUserDao.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.thinkcoder.dao.IUserDao">
<!--删除用户-->
<delete id="deleteUser" parameterType="java.lang.Integer">
delete * from user where id=#{id}
</delete>
</mapper>
MybatisTest类
public class MybatisTest{
//两个方法省略
@Test
public void testDelete(){
int res = userDao.deleteUser(49);
System.out.println("删除成功");
//提交事务
session.commit();
}
}
IUserDao接口
public interface IUserDao{
//根据id查询
User findById(Integer userId);
}
IUserDao.xml文件
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.thinkcoder.dao.IUserDao">
<!--根据id查询用户-->
<select id="findById" resultType="com.thinkcoder.domain.User" parameterType="int">
select * from user where id = #{uid}
</select>
</mapper>
MytatisTest类
public class MybatisTest {
private InputStream in;
private SqlSessionFactory factory;
private SqlSession session;
private IUserDao userDao;
@Test//测试根据Id查询
public void testFindById(){
User user = userDao.findById(49);
System.out.println(user);
}
//以下两个方法分别在测试方法自动前后执行
@Before //用于测试方法执行之前执行
public void init()throws Exception{
//1.读取配置文件,生成字节输入流
in = Resources.getResourceAsStream("SqlMapConfig.xml");
//2.获取SqlSessionFactory
factory = new SqlSessionFactoryBuilder().build(in);
//3.获取sqlsession对象
session = factory.openSession();
//4.获取dao的代理对象
userDao = session.getMapper(IUserDao.class);
}
@After //用于测试之后执行
public void realese()throws Exception{
session.close();
in.close();
}
}
运行结果
User{id=49, username='渣男', birthday=Sat May 23 23:00:06 CST 2020, sex='男', address='天堂'}
IUserDao接口
public interface IUserDao{
//根据名称模糊查询
List<User> findByName(String username);
}
IUserDao.xml文件
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.thinkcoder.dao.IUserDao">
<!--根据名字模糊查询-->
<select id="findByName" resultType="com.thinkcoder.domain.User" parameterType="String">
select * from user where username like #{username}
</select>
</mapper>
MybatisTest类
public class MybatisTest {
//上面的两个方法省略
@Test//测试模糊查询
public void testFindByName()throws Exception{
List<User> users = userDao.findByName("%王%");
for(User user : users){
System.out.println(user);
}
}
}
运行结果
User{id=46, username='王五', birthday=Wed Mar 07 17:37:26 CST 2018, sex='男', address='南京'}
User{id=50, username='王七', birthday=Sat May 23 20:00:06 CST 2020, sex='女', address='上海'}
IUserDao接口
public interface IUserDao{
//查询用户总数
int findTotal();
}
IUserDao.xml文件
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.thinkcoder.dao.IUserDao">
<!--查询总人数-->
<select id="findTotal" resultType="java.lang.Integer">
select COUNT(*) from user
</select>
</mapper>
MybatisTest类
public class MybatisTest {
//上面的两个方法省略
@Test //用于测试查询总人数方法
public void testTotal(){
int res = userDao.findTotal();
System.out.println(res);//7
}
}
修改User实体类,使其属性和数据库字段不一致,即不符合ORM思想
public class User implements Serializable {
//属性和数据库字段不一致
private Integer userId;
private String userName;
private Date userBirthday;
private String userSex;
private String userAddress;
//此处省略了getter和setter方法
在搭建Mybatis开发环境就实现了查询所有的功能,因此就不写了,哈哈
MybatisTest中类测试结果
User{userId=null, userName='张三', userBirthday=null, userSex='null', userAddress='null'}
User{userId=null, userName='李四', userBirthday=null, userSex='null', userAddress='null'}
User{userId=null, userName='王五', userBirthday=null, userSex='null', userAddress='null'}
User{userId=null, userName='周六', userBirthday=null, userSex='null', userAddress='null'}
Process finished with exit code 0
结果显示除了userName有值(mysql在widows中不区分大小写,即username和userName同效),其他值都为null
解决办法一:
在IUserDao.xml中,使用as别名
<mapper namespace="com.thinkcoder.dao.IUserDao">
<select id="findAll" resultType="com.thinkcoder.domain.User">
select id as userId,
username as userName,
birthday as userBirthday,
sex as userSex,
address as userAddress from user;
</select>
</mapper>
但是当数据库字段多了之后,写起来很费力
解决办法二:
在IUserDao.xml中,使用resultMap封装结果集
<mapper namespace="com.thinkcoder.dao.IUserDao">
<!--查询所有-->
<select id="findAll" resultMap="userMap">
select * from user
</select>
<!--定义resultMap-->
<!--id属性:给定表示用于select标签引用--><!--type属性:实体类全限定类名-->
<resultMap id="userMap" type="com.thinkcoder.domain.User">
<id column="id" property="userId"/>
<result column="username" property="userName"/>
<result column="sex" property="userSex"/>
<result column="address" property="userAddress"/>
<result column="birthday" property="userBirthday"/>
</resultMap>
</mapper>
resultMap子标签的属性说明
IUser.Dao.xml中的属性及字符
#{}内容格式是ognl表达式
增删改查的操作,在实际应用中是最多的也是基础,当然也不是特别难,但有所以咱们要好好掌握,后面博客继续更新Mybatis事务及复杂查询