MyBatis 是一款优秀的持久层框架,它支持自定义 SQL、存储过程以及高级映射。MyBatis 免除了几乎所有的 JDBC 代码以及设置参数和获取结果集的工作。MyBatis 可以通过简单的 XML 或注解来配置和映射原始类型、接口和 Java POJO为数据库中的记录。一般不写dao的实现类
基于XML配置的CURDdemo
1、创建User实体类
public class User implements Serializable {
private Integer userId;
private String userName;
private String userAddress;
private String userSex;
private Date userBirthday;
public Integer getUserId() {
return userId;
}
public void setUserId(Integer userId) {
this.userId = userId;
}
...
...
@Override
public String toString() {
return "User{" +
"id=" + userId +
", username='" + userName + '\'' +
", address='" + userAddress + '\'' +
", sex='" + userSex + '\'' +
", birthday=" + userBirthday +
'}';
}
}
2、创建持久层操作接口
/**
* 用户的持久层接口
*/
public interface IUserMapper {
/**
* 查询所有用户
* @return
*/
List<User> findAll();
/**
* 保存用户
* @param user
*/
void saveUser(User user);
/**
* 更新用户
* @param user
*/
void updateUser(User user);
/**
* 根据Id删除用户
* @param userId
*/
void deleteUser(Integer userId);
/**
* 根据id查询用户信息
* @param userId
* @return
*/
User findById(Integer userId);
/**
* 根据名称模糊查询用户信息
* @param username
* @return
*/
List<User> findByName(String username);
/**
* 查询总用户数
* @return
*/
Integer findTotal();
List<User> findByIdIn(@Param("ids")Set<Integer> ids);
}
3、创建并设置mybatis配置文件
<?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>
<!--使用typeAliases配置别名, -->
<typeAliases>
<!-- package指定实体类的包名,当指定之后,该包下的实体类都会注册别名,并且类名就是别名,不再区分大小写-->
<package name="com.kunjava.domain"></package>
</typeAliases>
<!--配置环境-->
<environments default="mysql">
<!-- 配置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"></property>
<property name="username" value="root"></property>
<property name="password" value="root"></property>
</dataSource>
</environment>
</environments>
<!-- 配置映射文件的位置 -->
<mappers>
<!--<mapper resource="com/kunjava/mapper/IUserMapper.xml"></mapper>-->
<!-- package标签是用于指定dao接口所在的包 -->
<package name="com.kunjava.mapper"></package>
</mappers>
</configuration>
4、设置对应的mapper配置文件
<mapper namespace="com.kunjava.mapper.IUserMapper">
<!-- 配置 查询结果的列名和实体类的属性名的对应关系 -->
<resultMap id="userMap" type="com.kunjava.domain.User">
<id column="id" property="userId" jdbcType="INTEGER"></id>
<result column="username" property="userName" jdbcType="VARCHAR"></result>
<result column="sex" property="userSex" jdbcType="VARCHAR"></result>
<result column="birthday" property="userBirthday" jdbcType="VARCHAR"></result>
<result column="address" property="userAddress" jdbcType="VARCHAR"></result>
</resultMap>
<!-- 查询所有 -->
<select id="findAll" resultMap="userMap">
select * from user;
</select>
<!-- 保存用户 -->
<insert id="saveUser" parameterType="user">
<!-- 配置插入操作后,获取插入数据的id -->
<selectKey keyProperty="userId" keyColumn="id" resultType="Integer" order="AFTER">
select last_insert_id();
</selectKey>
insert into user(username,address,sex,birthday)values(#{userName},#{userAddress},#{userSex},#{userBirthday});
</insert>
<!-- 更新用户 -->
<update id="updateUser" parameterType="User">
update user
<set>
<if test="userName != null">username = #{userName,jdbcType=VARCHAR}</if>
<if test="userAddress != null">address = #{userAddress,jdbcType=VARCHAR}</if>
<if test="userSex != null">sex = #{userSex,jdbcType=VARCHAR}</if>
<if test="userBirthday != null">birthday = #{userBirthday,jdbcType=DATE}</if>
</set>
where id = #{userId,jdbcType=INTEGER}
</update>
<!-- 删除用户-->
<delete id="deleteUser" parameterType="Integer">
delete from user where id = #{userId}
</delete>
<!-- 根据id查询用户 -->
<select id="findById" parameterType="Integer" resultMap="userMap">
select * from user where id = #{userId}
</select>
<!-- 根据名称模糊查询 -->
<select id="findByName" parameterType="String" resultMap="userMap">
select * from user where username like #{userName}
</select>
<!-- 获取用户的总记录条数 -->
<select id="findTotal" resultType="Integer">
select count(id) from user;
</select>
<!-- in()查询-->
<select id="findByIdIn" resultMap="userMap">
select * from user
<where>
<if test="ids!=null and ids.size()>0">
<foreach collection="ids" open=" and id in (" close=")" item="userId" separator=",">
#{userId}
</foreach>
</if>
</where>
</select>
</mapper>
5、测试
public class MybatisTest {
private InputStream in;
private SqlSession sqlSession;
private IUserMapper userMap;
@Before//用于在测试方法执行之前执行
public void init()throws Exception{
//1.读取配置文件,生成字节输入流
in = Resources.getResourceAsStream("SqlMapConfig.xml");
//2.获取SqlSessionFactory
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
//3.获取SqlSession对象
sqlSession = factory.openSession();
//4.获取mapper的代理对象
userMap = sqlSession.getMapper(IUserMapper.class);
}
@After//用于在测试方法执行之后执行
public void destroy()throws Exception{
//提交事务
sqlSession.commit();
//6.释放资源
sqlSession.close();
in.close();
}
/**
* 测试查询所有
*/
@Test
public void testFindAll(){
//5.执行查询所有方法
List<User> users = userMap.findAll();
for(User user : users){
System.out.println(user);
}
//User{id=1, username='老王', address='上海市', sex='男', birthday=Wed Jul 08 00:00:00 CST 2020}
//User{id=2, username='小王', address='北京市', sex='女', birthday=Thu Jul 09 00:00:00 CST 2020}
}
/**
* 测试保存操作
*/
@Test
public void testSave(){
User user = new User();
user.setUserName("帅小伙");
user.setUserAddress("南京市");
user.setUserSex("男");
user.setUserBirthday(new Date());
System.out.println("保存操作之前:"+user);
userMap.saveUser(user);
System.out.println("保存操作之后:"+user);
//保存操作之前:User{id=null, username='帅小伙', address='南京市', sex='男', birthday=Fri Jul 10 14:45:19 CST 2020}
//保存操作之后:User{id=3, username='帅小伙', address='南京市', sex='男', birthday=Fri Jul 10 14:45:19 CST 2020}
}
/**
* 测试更新操作
*/
@Test
public void testUpdate(){
User user = new User();
user.setUserId(3);
user.setUserName("新名字");
userMap.updateUser(user);
}
/**
* 测试删除操作
*/
@Test
public void testDelete(){
userMap.deleteUser(1);
}
/**
* 测试删除操作
*/
@Test
public void testFindOne(){
User user = userMap.findById(3);
System.out.println(user);
User{id=3, username='新名字', address='南京市', sex='男', birthday=Fri Jul 10 14:45:19 CST 2020}
}
/**
* 测试模糊查询操作
*/
@Test
public void testFindByName(){
//5.执行查询一个方法
List<User> users = userMap.findByName("新%");
for(User user : users){
System.out.println(user);
}
//User{id=3, username='新名字', address='南京市', sex='男', birthday=Fri Jul 10 14:45:19 CST 2020}
}
/**
* 测试查询总记录条数
*/
@Test
public void testFindTotal(){
//5.执行查询一个方法
int count = userMap.findTotal();
System.out.println(count);//3
}
/**
* 测试in()查询
*/
@Test
public void testFindByIdIn(){
Set<Integer> ids = new TreeSet<Integer>();
ids.add(1);
ids.add(3);
List<User> users = userMap.findByIdIn(ids);
for (User u:users){
System.out.println(u);
}
//User{id=1, username='老王', address='上海市', sex='男', birthday=Wed Jul 08 00:00:00 CST 2020}
//User{id=3, username='新名字', address='南京市', sex='男', birthday=Fri Jul 10 00:00:00 CST 2020}
}