Mybatis 注解实现基本 CRUD(十一)
程序员文章站
2022-07-12 22:39:11
...
项目结构图:
红框标记的和之前的项目相同
1.mybatis 的常用注解说明
@Insert:实现新增
@Update:实现更新
@Delete:实现删除
@Select:实现查询
@Result:实现结果集封装
@Results:可以与@Result 一起使用,封装多个结果集
@ResultMap:实现引用@Results 定义的封装
@One:实现一对一结果集封装
@Many:实现一对多结果集封装
@SelectProvider: 实现动态SQL映射
@CacheNamespace:实现注解二级缓存的使用
2.编写实体类
User.java
package com.wd.entity;
import java.io.Serializable;
import java.util.Date;
public class User implements Serializable {
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 + '\'' +
", birthyday=" + birthday +
", sex='" + sex + '\'' +
", address='" + address + '\'' +
'}';
}
}
3.使用注解方式开发持久层接口
UserMapper.java
package com.wd.mapper;
import com.wd.entity.User;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
import java.util.List;
/**
* 用户的持久层接口
* 在mybatis中针对,CRUD一共有四个注解
* @Select @Insert @Update @Delete
*/
public interface UserMapper {
/**
* 查询所有操作
* @return
*/
@Select("select * from user")
List<User> findAll();
/**
* 保存用户
* @param user
*/
@Insert("insert into user (username, address, sex, birthday) values (#{username}, #{address}, #{sex}, #{birthday})")
void saveUser(User user);
/**
* 更新用户
* @param user
*/
@Update("update user set username = #{username}, address = #{address}, sex = #{sex}, birthday = #{birthday} where id = #{id}")
void updateUser(User user);
/**
* 删除用户
* @param id
*/
@Delete("delete from user where id = #{id}")
void deleteUser(Integer id);
/**
* 根据id查询用户
* @param id
* @return
*/
@Select("select * from user where id = #{id}")
User findById(Integer id);
/**
* 根据用户名称模糊查询
* @param name
* @return
*/
//@Select("select * from user where username like #{name}")
@Select("select * from user where username like '%${value}%' ")
List<User> findUserByName(String name);
/**
* 查询总用户数量
* @return
*/
@Select("select count(*) from user ")
int findTotalUser();
}
4.编写 SqlMapConfig 配置文件
<?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">
<!--mybatis的主配置文件-->
<configuration>
<!--引入外部配置文件-->
<properties resource="jdbcConfig.properties"></properties>
<!--配置别名-->
<typeAliases>
<package name="com.wd.entity"/>
</typeAliases>
<!--配置环境-->
<environments default="mysql">
<!--配置mysql环境-->
<environment id="mysql">
<!--配置事务的类型-->
<transactionManager type="jdbc"></transactionManager>
<!--配置数据源(连接池)-->
<dataSource type="pooled">
<!--配置连接数据库的4个基本信息-->
<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>
<!--指定映射配置文件的位置,映射配置文件指的是每个mapper独立的配置文件
如果是用注解来配置的话,此处应该使用class属性指定被注解的mapper全限定类名
-->
<mappers>
<mapper class="com.wd.mapper.UserMapper"></mapper>
</mappers>
</configuration>
5.编写测试方法
AnnotationCRUDTest.java
public class AnnotationCRUDTest {
private InputStream in;
private SqlSessionFactory factory;
private SqlSession session;
private UserMapper userMapper;
@Before
public void init()throws Exception{
in = Resources.getResourceAsStream("SqlMapConfig.xml");
factory = new SqlSessionFactoryBuilder().build(in);
session = factory.openSession();
userMapper = session.getMapper(UserMapper.class);
}
@After
public void destroy()throws Exception{
session.commit();
session.close();
in.close();
}
@Test
public void testSave(){
User user = new User();
user.setUsername("mybatis annotation");
user.setAddress("beijing changpingqu");
userMapper.saveUser(user);
}
@Test
public void testUpdate(){
User user = new User();
user.setId(54);
user.setUsername("mybatis annotation update");
user.setAddress("beijingshi haidianqu");
user.setSex("m");
user.setBirthday(new Date());
userMapper.updateUser(user);
}
@Test
public void testDelete(){
userMapper.deleteUser(51);
}
@Test
public void testFindOne(){
User user = userMapper.findById(54);
System.out.println(user);
}
@Test
public void testFindByName(){
//List<User> users = userMapper.findUserByName("%mybatis%");
List<User> users = userMapper.findUserByName("mybatis");
for(User user : users){
System.out.println(user);
}
}
@Test
public void testFindTotal(){
int total = userMapper.findTotalUser();
System.out.println(total);
}
}
6.测试结果
testFindOne
testFindByName
testFindTotal
7.项目源代码
推荐阅读
-
Mybatis基于注解实现多表查询功能
-
【MyBatis】MyBatis实现CRUD操作
-
idea+spring4+springmvc+mybatis+maven实现简单增删改查CRUD
-
mybatis基于注解实现增删改查(详细介绍)
-
Mybatis使用注解实现一对一复杂关系映射及延迟加载
-
SpringBoot整合Mybatis(CRUD的实现)
-
SpringBoot整合Mybatis实现CRUD
-
Mybatis、Mybatis-Plus多表联合查询,通过注解实现,自定义SQL参考实现
-
day62 JavaWeb框架阶段—— Mybatis的注解开发&SSM框架整合(原始方式整合&Spring整合MyBatis& MyBatis的注解实现复杂映射开发)
-
mybatis注解——CRUD