Mybatis注解开发相关
一、项目构建
1、Java项目目录结构
2、在domain包下创建User实体类
package sun.domain; import java.io.Serializable;
import java.util.Date; /**
* @Classname User
* @Description TODO
* @Date 2020/9/13 14:07
* @Created by Administrator
*/
public class User implements Serializable {
private Integer id;
private String username;
private String address;
private String sex;
private Date birthday; 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 String getAddress() {
return address;
} public void setAddress(String address) {
this.address = address;
} public String getSex() {
return sex;
} public void setSex(String sex) {
this.sex = sex;
} public Date getBirthday() {
return birthday;
} public void setBirthday(Date birthday) {
this.birthday = birthday;
} @Override
public String toString() {
return "User{" +
"id=" + id +
", username='" + username + '\'' +
", address='" + address + '\'' +
", sex='" + sex + '\'' +
", birthday=" + birthday +
'}';
}
}
User实体类
3、在dao包下创建UserDao接口
package sun.dao; 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 sun.domain.User; import javax.jws.soap.SOAPBinding;
import java.util.List; /**
* @Classname UserDao
* @Description TODO
* @Date 2020/9/13 14:09
* @Created by Administrator
*/
public interface UserDao {
/**
* 查询所有用户
*/
@Select("select * from user")
List<User> findAll(); /**
* 根据id查user
*/
@Select("select * from user where id=#{id}")
User findUserById(Integer id); /**
* 模糊查询
*/
@Select("select * from user where username like #{name}")
List<User> findLike(String name); /**
* 查询记录总数
*/
@Select("select count(1) from user")
int findTotal(); /**
* 添加新用户
*/
@Insert("insert into user(username,birthday,sex,address) values(#{username},#{birthday},#{sex},#{address})")
void saveUser(User user); /**
* 更新用户信息
*/
@Update("update user set username=#{username},address=#{address},birthday=#{birthday},sex=#{sex} where id=#{id}")
void updateUser(User user); /**
* 删除用户
*/
@Delete("delete from user where id=#{id}")
void deleteUser(Integer id);
}
UserDao接口
4、在resource目录下创建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="jdbcConfig.properties"></properties> <typeAliases>
<package name="sun.domain"></package>
</typeAliases>
<!--配置环境-->
<environments default="mysql">
<!--配置mysql环境-->
<environment id="mysql">
<!--配置事务类型-->
<transactionManager type="JDBC"></transactionManager>
<!--配置数据库连接池-->
<dataSource type="POOLED">
<!--配置连接数据库基本信息-->
<property name="driver" value="${jdbc.driver}"></property>
<property name="url" value="${jdbc.url}"></property>
<property name="username" value="${jdbc.username}"></property>
<property name="password" value="${jdbc.password}"></property>
</dataSource>
</environment>
</environments> <mappers>
<package name="sun.dao"></package>
</mappers>
</configuration>
SqlMapConfig.xml
5、创建测试类
package sun.test; import org.apache.ibatis.annotations.Select;
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.After;
import org.junit.Before;
import org.junit.Test;
import sun.dao.UserDao;
import sun.domain.User; import java.io.InputStream;
import java.util.List; /**
* @Classname MybatisTest
* @Description TODO
* @Date 2020/9/13 14:57
* @Created by Administrator
*/
public class MybatisTest {
InputStream in;
SqlSessionFactoryBuilder builder;
SqlSessionFactory sessionFactory;
SqlSession sqlSession;
UserDao userDao; @Before
public void init() throws Exception{
in = Resources.getResourceAsStream("SqlMapConfig.xml");
builder = new SqlSessionFactoryBuilder();
sessionFactory = builder.build(in);
sqlSession = sessionFactory.openSession();
userDao = sqlSession.getMapper(UserDao.class);
}
@After
public void destory() throws Exception{
sqlSession.commit();
sqlSession.close();
in.close();
} @Test
public void findAllTest() throws Exception{
List<User> users = userDao.findAll();
for (User user : users) {
System.out.println(user);
}
} @Test
public void findOneTest() throws Exception{
User user = userDao.findUserById(48);
System.out.println(user);
} @Test
public void findLikeTest() throws Exception{
List<User> users = userDao.findLike("%王%");
for (User user : users) {
System.out.println(user);
}
} @Test
public void findTotalTest() throws Exception{
int total = userDao.findTotal();
System.out.println(total);
} @Test
public void saveUserTest() throws Exception{
User user = new User();
user.setUsername("kelvin");
user.setAddress("安徽省宿州市");
userDao.saveUser(user);
} @Test
public void updateTest() throws Exception{
User user = new User();
user.setId(49);
user.setUsername("kelvin");
user.setAddress("安徽省宿州市");
user.setSex("男");
userDao.updateUser(user);
} @Test
public void deleteTest(){
userDao.deleteUser(50);
}
}
测试类
二、构建实体类属性和数据库表字段对应关系
在接口方法中使用@Result来构建实体类属性和数据库表字段之间的关系,后面方法如果想要使用该关系可以使用@ResultMap进行使用。
package sun.dao; import org.apache.ibatis.annotations.*;
import sun.domain.User; import javax.jws.soap.SOAPBinding;
import java.util.List; /**
* @Classname UserDao
* @Description TODO
* @Date 2020/9/13 14:09
* @Created by Administrator
*/
public interface UserDao {
/**
* 查询所有用户
*/
@Select("select * from user")
@Results(id="userMap",value={
@Result(id=true,property = "user_id",column = "id"),
@Result(property = "user_name",column = "username"),
@Result(property = "user_sex",column = "sex"),
@Result(property = "user_address",column = "address"),
@Result(property = "user_birthday",column = "birthday"),
})
List<User> findAll(); /**
* 根据id查user
*/
@Select("select * from user where id=#{id}")
// @ResultMap(value = {"userMap"}) // 正规写法
@ResultMap("userMap") // 只有一个参数 简写
User findUserById(Integer id); /**
* 模糊查询
*/
@Select("select * from user where username like #{name}")
@ResultMap(value = {"userMap"})
List<User> findLike(String name); }
UserDao接口
三、一对一&一对多查询
创建一对一,一对多查询主要使用了@Result中的one属性和many属性。配置one或many中的select和fetchType即可。
Java项目目录结构
1、一对一
1)在domain下创建User和Account实体类
User类:
package sun.domain; import java.io.Serializable;
import java.util.Date;
import java.util.List; /**
* @Classname User
* @Description TODO
* @Date 2020/9/13 14:07
* @Created by Administrator
*/
public class User implements Serializable {
private Integer user_id;
private String user_name;
private String user_address;
private String user_sex;
private Date user_birthday;
private List<Account> accountList; public List<Account> getAccountList() {
return accountList;
} public void setAccountList(List<Account> accountList) {
this.accountList = accountList;
} public Integer getUser_id() {
return user_id;
} public void setUser_id(Integer user_id) {
this.user_id = user_id;
} public String getUser_name() {
return user_name;
} public void setUser_name(String user_name) {
this.user_name = user_name;
} public String getUser_address() {
return user_address;
} public void setUser_address(String user_address) {
this.user_address = user_address;
} public String getUser_sex() {
return user_sex;
} public void setUser_sex(String user_sex) {
this.user_sex = user_sex;
} public Date getUser_birthday() {
return user_birthday;
} public void setUser_birthday(Date user_birthday) {
this.user_birthday = user_birthday;
} @Override
public String toString() {
return "User{" +
"user_id=" + user_id +
", user_name='" + user_name + '\'' +
", user_address='" + user_address + '\'' +
", user_sex='" + user_sex + '\'' +
", user_birthday=" + user_birthday +
'}';
}
}
User
Account类:
package sun.domain; import java.io.Serializable; /**
* @Classname Account
* @Description TODO
* @Date 2020/9/14 8:50
* @Created by Administrator
*/
public class Account implements Serializable {
private Integer id;
private Integer uid;
private Double money;
private User user; public User getUser() {
return user;
} public void setUser(User user) {
this.user = user;
} public Integer getId() {
return id;
} public void setId(Integer id) {
this.id = id;
} public Integer getUid() {
return uid;
} public void setUid(Integer uid) {
this.uid = uid;
} public Double getMoney() {
return money;
} public void setMoney(Double money) {
this.money = money;
} @Override
public String toString() {
return "Account{" +
"id=" + id +
", uid=" + uid +
", money=" + money +
'}';
}
}
Account
2)在dao包下创建UserDao接口和AccountDao接口
UserDao接口:
package sun.dao; import org.apache.ibatis.annotations.*;
import org.apache.ibatis.mapping.FetchType;
import sun.domain.User; import javax.jws.soap.SOAPBinding;
import java.util.List; /**
* @Classname UserDao
* @Description TODO
* @Date 2020/9/13 14:09
* @Created by Administrator
*/
public interface UserDao {
/**
* 查询所有用户
*/
@Select("select * from user")
@Results(id="userMap",value={
@Result(id=true,property = "user_id",column = "id"),
@Result(property = "user_name",column = "username"),
@Result(property = "user_sex",column = "sex"),
@Result(property = "user_address",column = "address"),
@Result(property = "user_birthday",column = "birthday"),
@Result(property = "accountList",column = "id",
many = @Many(select = "sun.dao.AccountDao.findAccountById",
fetchType = FetchType.LAZY))
})
List<User> findAll(); /**
* 根据id查user
*/
@Select("select * from user where id=#{id}")
// @ResultMap(value = {"userMap"}) // 正规写法
@ResultMap("userMap") // 只有一个参数 简写
User findUserById(Integer id); }
UserDao接口
Account接口:
package sun.dao; import org.apache.ibatis.annotations.One;
import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.mapping.FetchType;
import sun.domain.Account; import java.util.List; /**
* @Classname AccountDao
* @Description TODO
* @Date 2020/9/14 8:52
* @Created by Administrator
*/
public interface AccountDao {
/**
* 查询所有数据
*/
@Select("select * from account")
//配置多对一(一对一)查询
@Results(id = "accountMap",value = {
@Result(id = true,property = "id",column = "id"),
@Result(property = "uid",column = "uid"),
@Result(property = "money",column = "money"),
@Result(property = "user",column = "uid",one = @One(select = "sun.dao.UserDao.findUserById",fetchType= FetchType.EAGER))
})
List<Account> findAll(); /**
* 根据id查user
*/
@Select("select * from account where uid=#{id}")
Account findAccountById(Integer id); }
AccountDao接口
3)创建主配置文件
4)测试
package sun.test; 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.After;
import org.junit.Before;
import org.junit.Test;
import sun.dao.AccountDao;
import sun.domain.Account;
import sun.domain.User; import java.io.InputStream;
import java.util.List; /**
* @Classname MybatisTest
* @Description TODO
* @Date 2020/9/13 14:57
* @Created by Administrator
*/
public class MybatisTest2 {
InputStream in;
SqlSessionFactoryBuilder builder;
SqlSessionFactory sessionFactory;
SqlSession sqlSession;
AccountDao accountDao; @Before
public void init() throws Exception{
in = Resources.getResourceAsStream("SqlMapConfig.xml");
builder = new SqlSessionFactoryBuilder();
sessionFactory = builder.build(in);
sqlSession = sessionFactory.openSession();
accountDao = sqlSession.getMapper(AccountDao.class);
}
@After
public void destory() throws Exception{
sqlSession.commit();
sqlSession.close();
in.close();
}
@Test
public void findAll(){
List<Account> all = accountDao.findAll();
for (Account account : all) {
System.out.println(account);
System.out.println(account.getUser());
}
}
}
2、一对多
1)同上
2)同上
3)同上
4)测试类
package sun.test; 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.After;
import org.junit.Before;
import org.junit.Test;
import sun.dao.UserDao;
import sun.domain.User; import java.io.InputStream;
import java.util.List; /**
* @Classname MybatisTest
* @Description TODO
* @Date 2020/9/13 14:57
* @Created by Administrator
*/
public class MybatisTest {
InputStream in;
SqlSessionFactoryBuilder builder;
SqlSessionFactory sessionFactory;
SqlSession sqlSession;
UserDao userDao; @Before
public void init() throws Exception {
in = Resources.getResourceAsStream("SqlMapConfig.xml");
builder = new SqlSessionFactoryBuilder();
sessionFactory = builder.build(in);
sqlSession = sessionFactory.openSession();
userDao = sqlSession.getMapper(UserDao.class);
} @After
public void destory() throws Exception {
sqlSession.commit();
sqlSession.close();
in.close();
} @Test
public void findAllTest() throws Exception {
List<User> users = userDao.findAll();
for (User user : users) {
System.out.println(user);
System.out.println(user.getAccountList());
}
} }
实体类属性和表字段对应关系、一对一、一对多查询及延迟加载均在@Result注解中配置。
Mybatis注解开发相关的更多相关文章
- Mybatis高级:Mybatis注解开发单表操作,Mybatis注解开发多表操作,构建sql语句,综合案例学生管理系统使用接口注解方式优化
知识点梳理 课堂讲义 一.Mybatis注解开发单表操作 *** 1.1 MyBatis的常用注解 之前我们在Mapper映射文件中编写的sql语句已经各种配置,其实是比较麻烦的 而这几年来注解开发越 ...
- Mybatis注解开发模糊查询
Mybatis注解开发模糊查询 一般在使用mybatis时都是采用xml文件保存sql语句 这篇文章讲一下在使用mybatis的注解开发时,如何进行模糊查询 模糊查询语句写法(在@Select注解中) ...
- 小D课堂-SpringBoot 2.x微信支付在线教育网站项目实战_3-2.使用Mybatis注解开发视频列表增删改查
笔记 2.使用Mybatis注解开发视频列表增删改查 讲解:使用Mybatis3.x注解方式 增删改查实操, 控制台打印sql语句 1.控制台打印sql语句 ...
- Spring Boot 使用Mybatis注解开发增删改查
使用逆向工程是遇到的错误 错误描述 org.apache.ibatis.binding.BindingException: Invalid bound statement (not found): c ...
- Mybatis注解开发多表一对一,一对多
Mybatis注解开发多表一对一,一对多 一对一 示例:帐户和用户的对应关系为,多个帐户对应一个用户,在实际开发中,查询一个帐户并同时查询该账户所属的用户信息,即立即加载且在mybatis中表现为一对 ...
- 【MyBatis】MyBatis 注解开发
MyBatis 注解开发 文章源码 环境搭建 Mybatis 也可以使用注解开发方式,这样就可以减少编写 Mapper 映射文件. 常用注解说明: @Insert 实现新增 @Update 实现更新 ...
- 【java框架】MyBatis(7)--MyBatis注解开发
1.MyBatis注解开发 1.1.Lombok的基本使用 Lombok是SpringBoot2.1.X版本与IDEA官方支持的一个插件,它是为简化POJO类中繁杂重复代码:geter/setter/ ...
- Mybatis注解开发(一对一)
其他代码访问:Mybatis注解开发基础操作 1.添加OrderMapper接口 public interface OrderMapper { // @Select("select *,o. ...
- Mybatis注解开发
mybatis 的常用注解: @Insert:实现新增 @Update:实现更新 @Delete:实现删除 @Select:实现查询 @Result:实现结果集封装 @Results:可以与 @Res ...
随机推荐
- 他们都说JVM能实际使用的内存比-Xmx指定的少?这是为什么呢
这确实是个挺奇怪的问题,特别是当最常出现的几种解释理由都被排除后,看来JVM并没有耍一些明显的小花招: -Xmx和-Xms是相等的,因此检测结果并不会因为堆内存增加而在运行时有所变化. 通过关闭自适应 ...
- 极简 Node.js 入门 - 2.4 定时器
极简 Node.js 入门系列教程:https://www.yuque.com/sunluyong/node 本文更佳阅读体验:https://www.yuque.com/sunluyong/node ...
- Jmeter(二十一) - 从入门到精通 - JMeter断言 - 上篇(详解教程)
1.简介 最近由于宏哥在搭建自己的个人博客可能更新的有点慢.断言组件用来对服务器的响应数据做验证,常用的断言是响应断言,其支持正则表达式.虽然我们的通过响应断言能够完成绝大多数的结果验证工作,但是JM ...
- 单元测试新方法:用setUp方法 @Before注释
public class CentralizedPUDMatchServicePacTest { PacMatchService pacMatchService; @Before public voi ...
- [NOIP2019] 划分
题目 题解 首先YY一个最简单的dp $dp[i][j]=min(dp[j][k]+(sum[i]-sum[j])^2 (sum[i]-sum[j]>=sum[j]-sum[k])$ $dp[i ...
- 数值分析案例:Newton插值预测2019城市(Asian)温度、Crout求解城市等温性的因素系数
数值分析案例:Newton插值预测2019城市(Asian)温度.Crout求解城市等温性的因素系数 文章目录 数值分析案例:Newton插值预测2019城市(Asian)温度.Crout求解城市等温 ...
- cpu相关信息(进程、线程、核...)
cpu的相关信息. 1.cpu 1.1 物理cpu 实际Server中插槽上的CPU个数.物理cpu数量,可以数不重复的 physical id 有几个 1.1.1 查看物理CPU的个数 cat /p ...
- Java面试题(Redis篇)
Redis 179.redis 是什么?都有哪些使用场景? Redis是一个开源的使用ANSI C语言编写.支持网络.可基于内存亦可持久化的日志型.Key-Value数据库,并提供多种语言的API. ...
- 符合SEO的网站标题应该怎么写
http://www.wocaoseo.com/thread-96-1-1.html 的seo网站标题既能提起读者的点击欲望,又能搜索引擎中获得好的排名,这两着之间有着有有一些联系,网站的标题若要从s ...
- Istio可观测性
Istio可观测性 Istio的可观测性包括metrics,日志,分布式链路跟踪以及可视化展示.下面主要介绍如何在istio中部署基于Prometheus的metrics监控,基于jaeger的链路跟 ...