一、项目构建

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注解开发相关的更多相关文章

  1. Mybatis高级:Mybatis注解开发单表操作,Mybatis注解开发多表操作,构建sql语句,综合案例学生管理系统使用接口注解方式优化

    知识点梳理 课堂讲义 一.Mybatis注解开发单表操作 *** 1.1 MyBatis的常用注解 之前我们在Mapper映射文件中编写的sql语句已经各种配置,其实是比较麻烦的 而这几年来注解开发越 ...

  2. Mybatis注解开发模糊查询

    Mybatis注解开发模糊查询 一般在使用mybatis时都是采用xml文件保存sql语句 这篇文章讲一下在使用mybatis的注解开发时,如何进行模糊查询 模糊查询语句写法(在@Select注解中) ...

  3. 小D课堂-SpringBoot 2.x微信支付在线教育网站项目实战_3-2.使用Mybatis注解开发视频列表增删改查

    笔记 2.使用Mybatis注解开发视频列表增删改查     讲解:使用Mybatis3.x注解方式 增删改查实操, 控制台打印sql语句              1.控制台打印sql语句      ...

  4. Spring Boot 使用Mybatis注解开发增删改查

    使用逆向工程是遇到的错误 错误描述 org.apache.ibatis.binding.BindingException: Invalid bound statement (not found): c ...

  5. Mybatis注解开发多表一对一,一对多

    Mybatis注解开发多表一对一,一对多 一对一 示例:帐户和用户的对应关系为,多个帐户对应一个用户,在实际开发中,查询一个帐户并同时查询该账户所属的用户信息,即立即加载且在mybatis中表现为一对 ...

  6. 【MyBatis】MyBatis 注解开发

    MyBatis 注解开发 文章源码 环境搭建 Mybatis 也可以使用注解开发方式,这样就可以减少编写 Mapper 映射文件. 常用注解说明: @Insert 实现新增 @Update 实现更新 ...

  7. 【java框架】MyBatis(7)--MyBatis注解开发

    1.MyBatis注解开发 1.1.Lombok的基本使用 Lombok是SpringBoot2.1.X版本与IDEA官方支持的一个插件,它是为简化POJO类中繁杂重复代码:geter/setter/ ...

  8. Mybatis注解开发(一对一)

    其他代码访问:Mybatis注解开发基础操作 1.添加OrderMapper接口 public interface OrderMapper { // @Select("select *,o. ...

  9. Mybatis注解开发

    mybatis 的常用注解: @Insert:实现新增 @Update:实现更新 @Delete:实现删除 @Select:实现查询 @Result:实现结果集封装 @Results:可以与 @Res ...

随机推荐

  1. 01 Arduino-点亮一盏LED灯

    01 硬件连接  图片比较丑 特别说明:一般默认为二极管灯的压降是 2V 均值电流为15ma,所以如果接在5V的电源上面,串联接的电阻值为200欧姆左右,可做适当调整 切记不允许把LED灯直接并联在5 ...

  2. Java并发---并发理论

    一.如何理解线程安全 在多线程中稍微不注意就会出现线程安全问题,那么什么是线程安全问题? 我的认识是.在多线程下代码执行的结果和预期的正确的结果不一致,该代码就是线程不安全的,否则就是线程安全的 在深 ...

  3. 【算法•日更•第十期】树型动态规划&区间动态规划:加分二叉树题解

    废话不多说,直接上题: 1580:加分二叉树 时间限制: 1000 ms         内存限制: 524288 KB提交数: 121     通过数: 91 [题目描述] 原题来自:NOIP 20 ...

  4. python3 输出中文、日文等等乱码问题的解决办法

    例如: url = 'https://zozo.jp/shop/mrolive/goods-sale/44057773/?did=73037089' resp = requests.get(url=u ...

  5. unity探索者之微信支付,非第三方插件

    版权声明:本文为原创文章,转载请声明http://www.cnblogs.com/unityExplorer/p/8404604.html 相比微信的登录和分享功能,微信支付sdk的接入显得相当简单, ...

  6. DDD与Repository

    Repository已经不是什么新鲜概念了.DDD模型自2004年提出,发展至今已经16年了.但是不少企业却无法实施,其原因也很简单:DDD是基于需求的,而很多并不理解需求:DDD是容易实现的,而很多 ...

  7. C++炮台实验

    炮台实验 蒜头君在玩一个战争模拟游戏,他有高度为 1,2,3,... ,n的炮台各一个,他需要把这 n个炮台从左往右排成一行,并且炮口都朝向右边. 在这个游戏中,所有炮台发射的炮弹会摧毁前方所有高度比 ...

  8. Reliable Federated Learning for Mobile Networks

    郑重声明:原文参见标题,如有侵权,请联系作者,将会撤销发布! 以下是对本文关键部分的摘抄翻译,详情请参见原文. arXiv: 1910.06837v1 [cs.CR] 14 Oct 2019 Abst ...

  9. 7. Jackson用树模型处理JSON是必备技能,不信你看

    每棵大树,都曾只是一粒种子.本文已被 https://www.yourbatman.cn 收录,里面一并有Spring技术栈.MyBatis.JVM.中间件等小而美的专栏供以免费学习.关注公众号[BA ...

  10. App 自动化,Appium 凭什么使用 UiAutomator2?

    1. UiAutomator2 是什么 可能很多人对 UiAutomator2 和 UiAutomator 傻傻分不清楚 UiAutomator 是 Google 开发的一款运行在 Android 设 ...