Mybatis注解开发笔记
Mybatis注解开发(笔记)
- 欢迎来到菜鸟研究所
- 创建新的Maven项目
- 配置文件
- prom.xml
- log4j.properties
- jdbcConfig.properties
- SqlMapComfig.xml
- 数据库结构和内容
- 简单的CRUD(增查改删)实现
- User.java
- 查询所用户
- 增加用户
- 修改用户信息
- 删除用户
- CRUD的其他基础操作
- 通过id查询用户
- 根据用户名进行模糊查询
- 查询用户数量
- 复杂关系映射
- 复杂关系映射的注解说明
- 一对一
- 一对多
- 附录
欢迎来到菜鸟研究所
本文主要介绍Mybatis的注解开发基础,期待大佬的指点,对本文有疑惑的朋友可以加QQ:3489968775进行询问。
本文用到的开发工具是idea,数据库是mysql。
创建新的Maven项目
配置文件
prom.xml
<?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.jindashen</groupId><artifactId>annotation01</artifactId><version>1.0-SNAPSHOT</version><packaging>jar</packaging><dependencies><dependency><groupId>org.mybatis</groupId><artifactId>mybatis</artifactId><version>3.4.5</version></dependency><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>5.1.6</version></dependency><dependency><groupId>log4j</groupId><artifactId>log4j</artifactId><version>1.2.12</version></dependency><dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>4.10</version></dependency></dependencies>
</project>
再创建如图所示的目录结构:
再在resources文件目录下导入jdbcConfig.properties和log4j.properties
log4j.properties
# Set root category priority to INFO and its only appender to CONSOLE.
#log4j.rootCategory=INFO, CONSOLE debug info warn error fatal
log4j.rootCategory=debug, CONSOLE, LOGFILE# Set the enterprise logger category to FATAL and its only appender to CONSOLE.
log4j.logger.org.apache.axis.enterprise=FATAL, CONSOLE# CONSOLE is set to be a ConsoleAppender using a PatternLayout.
log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
log4j.appender.CONSOLE.layout.ConversionPattern=%d{ISO8601} %-6r [%15.15t] %-5p %30.30c %x - %m\n# LOGFILE is set to be a File appender using a PatternLayout.
log4j.appender.LOGFILE=org.apache.log4j.FileAppender
log4j.appender.LOGFILE.File=d:\axis.log
log4j.appender.LOGFILE.Append=true
log4j.appender.LOGFILE.layout=org.apache.log4j.PatternLayout
log4j.appender.LOGFILE.layout.ConversionPattern=%d{ISO8601} %-6r [%15.15t] %-5p %30.30c %x - %m\n
jdbcConfig.properties
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/数据库名称
jdbc.username=mysql用户名
jdbc.password=mysql密码
随后在resources下进行SqlMapComfig.xml文件的配置
SqlMapComfig.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configurationPUBLIC "-//mybatis.org//DTD Config 3.0//EN""http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration><properties resource="jdbcConfig.properties" ></properties><!--使用typeAliases配置别名,它只能配置domain中类的别名--><typeAliases><package name="com.jindashen.domain"/></typeAliases><!--配置环境--><environments default="mysql"><!--配置mysql环境--><environment id="mysql"><!--配置事务--><transactionManager type="JDBC"></transactionManager><!--配置连接池--><dataSource type="POOLED"><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><!--指定带有注解的dao接口所在位置--><mappers><!--package用于指定dao接口所在的包,当指定完之后就不需要再写mapper以及resource或者classl--><package name="com.jindashen.dao"/></mappers>
</configuration>
数据库结构和内容
user表中的数据
简单的CRUD(增查改删)实现
先通过数据表的结构创建出与之对应的实现类User.java并实现Serializable接口,再在dao路径下创建UserDao接口,在UserDao中编写想要实现的功能
User.java
package com.jindashen.domian;import java.util.Date;/*** @program: annotation* @description:* @author: Mr.King* @create: 2021-09-04 10:54**/public class User {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;}@Overridepublic String toString() {return "User{" +"id=" + id +", username='" + username + '\'' +", address='" + address + '\'' +", sex='" + sex + '\'' +", birthday=" + birthday +'}';}
}
查询所用户
/*** @Description: 查询所有用户* @Param: []* @return: java.util.List<com.jindashen.domain.User>* @Author: Mr.King* @Date: 2021/9/4*/@Select(value="select * from user")List<User> findAll();
测试的部分代码(完整代码见附录):
/*** @Description: 查询所有* @Param: []* @return: void* @Author: Mr.King* @Date: 2021/9/4*/@Testpublic void testFindAll(){List<User> users = userDao.findAll();for (User user : users) {System.out.println(user);}}
测试结果:
2021-09-04 11:36:05,660 151 [ main] DEBUG .apache.ibatis.io.ResolverUtil - Checking to see if class com.jindashen.dao.UserDao matches criteria [is assignable to Object]
2021-09-04 11:36:05,693 184 [ main] DEBUG ansaction.jdbc.JdbcTransaction - Opening JDBC Connection
2021-09-04 11:36:05,853 344 [ main] DEBUG source.pooled.PooledDataSource - Created connection 2107443224.
2021-09-04 11:36:05,853 344 [ main] DEBUG .jindashen.dao.UserDao.findAll - ==> Preparing: select * from user
2021-09-04 11:36:05,884 375 [ main] DEBUG .jindashen.dao.UserDao.findAll - ==> Parameters:
2021-09-04 11:36:05,900 391 [ main] DEBUG .jindashen.dao.UserDao.findAll - <== Total: 9
User{id=41, username='Tonny', address='USA', sex='男', birthday=Tue Feb 27 17:47:08 CST 2018}
User{id=42, username='小二王', address='China', sex='女', birthday=Fri Mar 02 15:09:37 CST 2018}
User{id=43, username='小二王', address='China', sex='女', birthday=Sun Mar 04 11:34:34 CST 2018}
User{id=45, username='金大神', address='China', sex='男', birthday=Sun Mar 04 12:04:06 CST 2018}
User{id=46, username='老王', address='China', sex='男', birthday=Wed Mar 07 17:37:26 CST 2018}
User{id=48, username='海绵宝宝', address='China', sex='女', birthday=Thu Mar 08 11:44:00 CST 2018}
User{id=59, username='Anny', address='USA', sex='女', birthday=Tue Aug 31 19:40:44 CST 2021}
User{id=62, username='Tom', address='USA', sex='男', birthday=Tue Aug 31 20:16:32 CST 2021}
User{id=65, username='Ben', address='USA', sex='男', birthday=Fri Sep 03 18:51:20 CST 2021}
2021-09-04 11:36:05,900 391 [ main] DEBUG ansaction.jdbc.JdbcTransaction - Closing JDBC Connection [com.mysql.jdbc.JDBC4Connection@7d9d0818]
2021-09-04 11:36:05,900 391 [ main] DEBUG source.pooled.PooledDataSource - Returned connection 2107443224 to pool.
增加用户
/*** @Description: 保存用户* @Param: [user]* @return: void* @Author: Mr.King* @Date: 2021/9/4*/@Insert(value = "insert into user(username,address,sex,birthday) values(#{username},#{address},#{sex},#{birthday})")void saveUser(User user);
测试的部分代码(完整代码见附录):
/*** @Description: 保存用户信息* @Param: []* @return: void* @Author: Mr.King* @Date: 2021/9/4*/@Testpublic void testInsert(){User user = new User();user.setUsername("Ben");user.setAddress("USA");user.setSex("男");user.setBirthday(new Date());userDao.saveUser(user);}
测试结果
2021-09-04 11:39:41,304 107 [ main] DEBUG .apache.ibatis.io.ResolverUtil - Checking to see if class com.jindashen.dao.UserDao matches criteria [is assignable to Object]
2021-09-04 11:39:41,342 145 [ main] DEBUG ansaction.jdbc.JdbcTransaction - Opening JDBC Connection
2021-09-04 11:39:41,497 300 [ main] DEBUG source.pooled.PooledDataSource - Created connection 1855610584.
2021-09-04 11:39:41,513 316 [ main] DEBUG jindashen.dao.UserDao.saveUser - ==> Preparing: insert into user(username,address,sex,birthday) values(?,?,?,?)
2021-09-04 11:39:41,595 398 [ main] DEBUG jindashen.dao.UserDao.saveUser - ==> Parameters: Ben(String), USA(String), 男(String), 2021-09-04 11:39:41.336(Timestamp)
2021-09-04 11:39:41,595 398 [ main] DEBUG jindashen.dao.UserDao.saveUser - <== Updates: 1
2021-09-04 11:39:41,595 398 [ main] DEBUG ansaction.jdbc.JdbcTransaction - Closing JDBC Connection [com.mysql.jdbc.JDBC4Connection@6e9a5ed8]
2021-09-04 11:39:41,595 398 [ main] DEBUG source.pooled.PooledDataSource - Returned connection 1855610584 to pool.
修改用户信息
/*** @Description: 更新用户信息* @Param: [user]* @return: void* @Author: Mr.King* @Date: 2021/9/4*/@Update(value = "update user set username=#{username},sex=#{sex},birthday=#{birthday},address=#{address} where id=#{id}")void updateUser(User user);
测试的部分代码(完整代码见附录):
/*** @Description: 更新用户信息* @Param: []* @return: void* @Author: Mr.King* @Date: 2021/9/4*/@Testpublic void testUpdate(){User user = new User();user.setId(66);user.setUsername("Ben1");user.setAddress("USA1");user.setSex("男");user.setBirthday(new Date());userDao.updateUser(user);}
测试结果
2021-09-04 11:48:06,574 116 [ main] DEBUG .apache.ibatis.io.ResolverUtil - Checking to see if class com.jindashen.dao.UserDao matches criteria [is assignable to Object]
2021-09-04 11:48:06,605 147 [ main] DEBUG ansaction.jdbc.JdbcTransaction - Opening JDBC Connection
2021-09-04 11:48:06,767 309 [ main] DEBUG source.pooled.PooledDataSource - Created connection 1855610584.
2021-09-04 11:48:06,767 309 [ main] DEBUG ndashen.dao.UserDao.updateUser - ==> Preparing: update user set username=?,sex=?,birthday=?,address=? where id=?
2021-09-04 11:48:06,814 356 [ main] DEBUG ndashen.dao.UserDao.updateUser - ==> Parameters: Ben1(String), 男(String), 2021-09-04 11:48:06.605(Timestamp), USA1(String), 66(Integer)
2021-09-04 11:48:06,830 372 [ main] DEBUG ndashen.dao.UserDao.updateUser - <== Updates: 1
2021-09-04 11:48:06,831 373 [ main] DEBUG ansaction.jdbc.JdbcTransaction - Closing JDBC Connection [com.mysql.jdbc.JDBC4Connection@6e9a5ed8]
2021-09-04 11:48:06,831 373 [ main] DEBUG source.pooled.PooledDataSource - Returned connection 1855610584 to pool.
删除用户
/*** @Description: 删除用户信息* @Param: [id]* @return: void* @Author: Mr.King* @Date: 2021/9/4*/@Delete(value="delete from user where id=#{id}")void deleteUserById(Integer id);
测试的部分代码(完整代码见附录):
/*** @Description: 删除用户信息* @Param: []* @return: void* @Author: Mr.King* @Date: 2021/9/4*/@Testpublic void testDelete(){userDao.deleteUserById(66);}
测试结果
2021-09-04 11:54:30,056 130 [ main] DEBUG .apache.ibatis.io.ResolverUtil - Checking to see if class com.jindashen.dao.UserDao matches criteria [is assignable to Object]
2021-09-04 11:54:30,093 167 [ main] DEBUG ansaction.jdbc.JdbcTransaction - Opening JDBC Connection
2021-09-04 11:54:30,259 333 [ main] DEBUG source.pooled.PooledDataSource - Created connection 1855610584.
2021-09-04 11:54:30,264 338 [ main] DEBUG hen.dao.UserDao.deleteUserById - ==> Preparing: delete from user where id=?
2021-09-04 11:54:30,286 360 [ main] DEBUG hen.dao.UserDao.deleteUserById - ==> Parameters: 66(Integer)
2021-09-04 11:54:30,294 368 [ main] DEBUG hen.dao.UserDao.deleteUserById - <== Updates: 1
2021-09-04 11:54:30,294 368 [ main] DEBUG ansaction.jdbc.JdbcTransaction - Closing JDBC Connection [com.mysql.jdbc.JDBC4Connection@6e9a5ed8]
2021-09-04 11:54:30,294 368 [ main] DEBUG source.pooled.PooledDataSource - Returned connection 1855610584 to pool.
CRUD的其他基础操作
通过id查询用户
/*** @Description: 通过id查询用户* @Param: [id]* @return: com.jindashen.domain.User* @Author: Mr.King* @Date: 2021/9/4*/@Select(value = "select * from user where id=#{id}")User findUserById(Integer id);
测试的部分代码(完整代码见附录):
/*** @Description: 测试通过id查询用户* @Param: []* @return: void* @Author: Mr.King* @Date: 2021/9/4*/@Testpublic void testFindUserById(){User user = userDao.findUserById(65);System.out.println(user);}
测试结果
2021-09-04 11:55:19,122 133 [ main] DEBUG .apache.ibatis.io.ResolverUtil - Checking to see if class com.jindashen.dao.UserDao matches criteria [is assignable to Object]
2021-09-04 11:55:19,163 174 [ main] DEBUG ansaction.jdbc.JdbcTransaction - Opening JDBC Connection
2021-09-04 11:55:19,324 335 [ main] DEBUG source.pooled.PooledDataSource - Created connection 725680028.
2021-09-04 11:55:19,326 337 [ main] DEBUG ashen.dao.UserDao.findUserById - ==> Preparing: select * from user where id=?
2021-09-04 11:55:19,351 362 [ main] DEBUG ashen.dao.UserDao.findUserById - ==> Parameters: 65(Integer)
2021-09-04 11:55:19,368 379 [ main] DEBUG ashen.dao.UserDao.findUserById - <== Total: 1
User{id=65, username='Ben', address='USA', sex='男', birthday=Fri Sep 03 18:51:20 CST 2021}
2021-09-04 11:55:19,372 383 [ main] DEBUG ansaction.jdbc.JdbcTransaction - Closing JDBC Connection [com.mysql.jdbc.JDBC4Connection@2b40ff9c]
2021-09-04 11:55:19,372 383 [ main] DEBUG source.pooled.PooledDataSource - Returned connection 725680028 to pool.
根据用户名进行模糊查询
/*** @Description: 根据用户名进行模糊查询* @Param: [username]* @return: java.util.List<com.jindashen.domain.User>* @Author: Mr.King* @Date: 2021/9/4*/@Select(value = "select * from user where username like #{username}")List<User> findUserByName(String username);
测试的部分代码(完整代码见附录):
/*** @Description: 测试根据用户名进行模糊查询* @Param: []* @return: void* @Author: Mr.King* @Date: 2021/9/4*/@Testpublic void testFindUserByName(){List<User> users = userDao.findUserByName("%王%");for (User user : users) {System.out.println(user);}}
测试结果
2021-09-04 11:55:58,540 158 [ main] DEBUG .apache.ibatis.io.ResolverUtil - Checking to see if class com.jindashen.dao.UserDao matches criteria [is assignable to Object]
2021-09-04 11:55:58,591 209 [ main] DEBUG ansaction.jdbc.JdbcTransaction - Opening JDBC Connection
2021-09-04 11:55:58,789 407 [ main] DEBUG source.pooled.PooledDataSource - Created connection 725680028.
2021-09-04 11:55:58,790 408 [ main] DEBUG hen.dao.UserDao.findUserByName - ==> Preparing: select * from user where username like ?
2021-09-04 11:55:58,821 439 [ main] DEBUG hen.dao.UserDao.findUserByName - ==> Parameters: %王%(String)
2021-09-04 11:55:58,843 461 [ main] DEBUG hen.dao.UserDao.findUserByName - <== Total: 3
User{id=42, username='小二王', address='China', sex='女', birthday=Fri Mar 02 15:09:37 CST 2018}
User{id=43, username='小二王', address='China', sex='女', birthday=Sun Mar 04 11:34:34 CST 2018}
User{id=46, username='老王', address='China', sex='男', birthday=Wed Mar 07 17:37:26 CST 2018}
2021-09-04 11:55:58,849 467 [ main] DEBUG ansaction.jdbc.JdbcTransaction - Closing JDBC Connection [com.mysql.jdbc.JDBC4Connection@2b40ff9c]
2021-09-04 11:55:58,849 467 [ main] DEBUG source.pooled.PooledDataSource - Returned connection 725680028 to pool.
查询用户数量
/*** @Description: 查询用户数量* @Param: []* @return: int* @Author: Mr.King* @Date: 2021/9/4*/@Select(value = "select count(*) from user")int findTotalUser();
测试的部分代码(完整代码见附录):
/*** @Description: 测试查询用户数量* @Param: []* @return: void* @Author: Mr.King* @Date: 2021/9/4*/@Testpublic void testFindTotalUser(){Integer num = userDao.findTotalUser();System.out.println(num);}
测试结果
2021-09-04 11:56:29,506 164 [ main] DEBUG .apache.ibatis.io.ResolverUtil - Checking to see if class com.jindashen.dao.UserDao matches criteria [is assignable to Object]
2021-09-04 11:56:29,547 205 [ main] DEBUG ansaction.jdbc.JdbcTransaction - Opening JDBC Connection
2021-09-04 11:56:29,757 415 [ main] DEBUG source.pooled.PooledDataSource - Created connection 2107443224.
2021-09-04 11:56:29,761 419 [ main] DEBUG shen.dao.UserDao.findTotalUser - ==> Preparing: select count(*) from user
2021-09-04 11:56:29,818 476 [ main] DEBUG shen.dao.UserDao.findTotalUser - ==> Parameters:
2021-09-04 11:56:29,840 498 [ main] DEBUG shen.dao.UserDao.findTotalUser - <== Total: 1
9
2021-09-04 11:56:29,841 499 [ main] DEBUG ansaction.jdbc.JdbcTransaction - Closing JDBC Connection [com.mysql.jdbc.JDBC4Connection@7d9d0818]
2021-09-04 11:56:29,841 499 [ main] DEBUG source.pooled.PooledDataSource - Returned connection 2107443224 to pool.
复杂关系映射
新建一个Maven项目,配置文件同上。再通过数据库中account表的结构创建Account类和相应的Dao接口。
复杂关系映射的注解说明
@Results 注解
代替的是标签 < resultMap >
该注解中可以使用单个@Result 注解,也可以使用@Result 集合
@Results({
@Result(),
@Result()
})或
@Results(@Result())
@Resutl 注解
代替了 < id >标签和< result >标签
@Result 中 属性介绍:
id 是否是主键字段
column 数据库的列名
property 需要装配的属性名
one 需要使用的@One 注解(@Result((one=@One)())
)
many 需要使用的@Many 注解(@Result((many=@many)())
)
@One 注解(一对一)
代替了< assocation >标签,是多表查询的关键,在注解中用来指定子查询返回单一对象。
@One 注解属性介绍:
select 指定用来多表查询的 sqlmapper
fetchType 会覆盖全局的配置参数 lazyLoadingEnabled。。
使用格式:
@Result(column=" ",property=" ",one=@One(select=""))
@Many 注解(多对一)
代替了< Collection >标签,是是多表查询的关键,在注解中用来指定子查询返回对象集合。
注意:聚集元素用来处理“一对多”的关系。需要指定映射的 Java 实体类的属性,属性的 javaType
(一般为 ArrayList)但是注解中可以不定义;
使用格式:
@Result(property=" ",column=" ",many=@Many(select=""))
一对一
在Account类中添加
//一对一的映射:一个账户只能属于一个用户private User user;
并生成get(),set()方法。
此时Account类的代码如下:
package com.jindashen.domain;import java.io.Serializable;
import java.util.List;/*** @program: annoOne2Many* @description:* @author: Mr.King* @create: 2021-09-03 19:21**/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;}@Overridepublic String toString() {return "Account{" +"id=" + id +", uid=" + uid +", money=" + money +'}';}
}
AccountDao代码:
package com.jindashen.dao;import com.jindashen.domain.Account;
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 java.util.List;/*** @program: annoOne2Many* @description:* @author: Mr.King* @create: 2021-09-03 19:23**/public interface AccountDao {/*** @Description: 查询所有用户,并且获取每个用户所属的用户信息* @Param: []* @return: java.util.List<com.jindashen.domain.Account>* @Author: Mr.King* @Date: 2021/9/3*/@Select(value = "select * from account")@Results(id="accountMap",value = {@Result(id=true,column = "id",property = "id"),@Result(column = "uid",property = "uid"),@Result(column = "money",property = "money"),@Result(property = "user",column = "uid",one=@One(select="com.jindashen.dao.UserDao.findUserById",fetchType= FetchType.EAGER))})List<Account> findAll();@Select(value = "select * from account where uid=#{uid}")List<Account> findAccountByUid(Integer uid);}
测试代码:
/*** @Description: 测试查询所有用户,并且获取每个用户所属的用户信息* @Param: []* @return: void* @Author: Mr.King* @Date: 2021/9/3*/@Testpublic void testFindAll(){List<Account> accounts = accountDao.findAll();for (Account account : accounts) {System.out.println("--------账户信息----------");System.out.println(account);System.out.println("--------用户信息----------");System.out.println(account.getUser());}}
测试结果:
2021-09-04 13:09:35,777 199 [ main] DEBUG .apache.ibatis.io.ResolverUtil - Checking to see if class com.jindashen.dao.AccountDao matches criteria [is assignable to Object]
2021-09-04 13:09:35,777 199 [ main] DEBUG .apache.ibatis.io.ResolverUtil - Checking to see if class com.jindashen.dao.UserDao matches criteria [is assignable to Object]
2021-09-04 13:09:35,824 246 [ main] DEBUG ansaction.jdbc.JdbcTransaction - Opening JDBC Connection
2021-09-04 13:09:36,002 424 [ main] DEBUG source.pooled.PooledDataSource - Created connection 1464191502.
2021-09-04 13:09:36,002 424 [ main] DEBUG ndashen.dao.AccountDao.findAll - ==> Preparing: select * from account
2021-09-04 13:09:36,042 464 [ main] DEBUG ndashen.dao.AccountDao.findAll - ==> Parameters:
2021-09-04 13:09:36,062 484 [ main] DEBUG com.jindashen.dao.UserDao - Cache Hit Ratio [com.jindashen.dao.UserDao]: 0.0
2021-09-04 13:09:36,062 484 [ main] DEBUG ashen.dao.UserDao.findUserById - ====> Preparing: select * from user where id=?
2021-09-04 13:09:36,062 484 [ main] DEBUG ashen.dao.UserDao.findUserById - ====> Parameters: 41(Integer)
2021-09-04 13:09:36,143 565 [ main] DEBUG ashen.dao.UserDao.findUserById - <==== Total: 1
2021-09-04 13:09:36,143 565 [ main] DEBUG com.jindashen.dao.UserDao - Cache Hit Ratio [com.jindashen.dao.UserDao]: 0.0
2021-09-04 13:09:36,143 565 [ main] DEBUG ashen.dao.UserDao.findUserById - ====> Preparing: select * from user where id=?
2021-09-04 13:09:36,143 565 [ main] DEBUG ashen.dao.UserDao.findUserById - ====> Parameters: 45(Integer)
2021-09-04 13:09:36,144 566 [ main] DEBUG ashen.dao.UserDao.findUserById - <==== Total: 1
2021-09-04 13:09:36,145 567 [ main] DEBUG ndashen.dao.AccountDao.findAll - <== Total: 3
--------账户信息----------
Account{id=1, uid=41, money=1000.0}
--------用户信息----------
2021-09-04 13:09:36,146 568 [ main] DEBUG ao.AccountDao.findAccountByUid - ==> Preparing: select * from account where uid=?
2021-09-04 13:09:36,146 568 [ main] DEBUG ao.AccountDao.findAccountByUid - ==> Parameters: 41(Integer)
2021-09-04 13:09:36,147 569 [ main] DEBUG ao.AccountDao.findAccountByUid - <== Total: 2
User{userId=41, userName='Tonny', userAddress='USA', userSex='男', userBirthday=Tue Feb 27 17:47:08 CST 2018}
--------账户信息----------
Account{id=2, uid=45, money=1000.0}
--------用户信息----------
2021-09-04 13:09:36,148 570 [ main] DEBUG ao.AccountDao.findAccountByUid - ==> Preparing: select * from account where uid=?
2021-09-04 13:09:36,148 570 [ main] DEBUG ao.AccountDao.findAccountByUid - ==> Parameters: 45(Integer)
2021-09-04 13:09:36,149 571 [ main] DEBUG ao.AccountDao.findAccountByUid - <== Total: 1
User{userId=45, userName='金大神', userAddress='China', userSex='男', userBirthday=Sun Mar 04 12:04:06 CST 2018}
--------账户信息----------
Account{id=3, uid=41, money=2000.0}
--------用户信息----------
User{userId=41, userName='Tonny', userAddress='USA', userSex='男', userBirthday=Tue Feb 27 17:47:08 CST 2018}
2021-09-04 13:09:36,161 583 [ main] DEBUG ansaction.jdbc.JdbcTransaction - Closing JDBC Connection [com.mysql.jdbc.JDBC4Connection@5745ca0e]
2021-09-04 13:09:36,161 583 [ main] DEBUG source.pooled.PooledDataSource - Returned connection 1464191502 to pool.
一对多
在User类中添加
//一对多关系映射:一个用户对应多个账户private List<Account> accounts;
并生成get(),set()方法。
此时User类的代码如下:
package com.jindashen.domain;import java.io.Serializable;
import java.util.Date;
import java.util.List;/*** @program: annotation01* @description: user对象* @author: Mr.King* @create: 2021-09-03 18:06**/public class User implements Serializable {private Integer userId;private String userName;private String userAddress;private String userSex;private Date userBirthday;//一对多关系映射:一个用户对应多个账户private List<Account> accounts;public List<Account> getAccounts() {return accounts;}public void setAccounts(List<Account> accounts) {this.accounts = accounts;}public Integer getUserId() {return userId;}public void setUserId(Integer userId) {this.userId = userId;}public String getUserName() {return userName;}public void setUserName(String userName) {this.userName = userName;}public String getUserAddress() {return userAddress;}public void setUserAddress(String userAddress) {this.userAddress = userAddress;}public String getUserSex() {return userSex;}public void setUserSex(String userSex) {this.userSex = userSex;}public Date getUserBirthday() {return userBirthday;}public void setUserBirthday(Date userBirthday) {this.userBirthday = userBirthday;}@Overridepublic String toString() {return "User{" +"userId=" + userId +", userName='" + userName + '\'' +", userAddress='" + userAddress + '\'' +", userSex='" + userSex + '\'' +", userBirthday=" + userBirthday +'}';}
}
UserDao代码:
package com.jindashen.dao;import com.jindashen.domain.User;
import org.apache.ibatis.annotations.*;
import org.apache.ibatis.mapping.FetchType;import java.util.List;/*** @program: annotation01* @description: userDao接口* @author: Mr.King* @create: 2021-09-03 18:10**/
@CacheNamespace(blocking = true)
public interface UserDao {/*** @Description: 查询所有用户* @Param: []* @return: java.util.List<com.jindashen.domain.User>* @Author: Mr.King* @Date: 2021/9/3*/@Select(value="select * from user")@Results(id="userMap",value={@Result(id=true,column = "id",property = "userId"),@Result(column = "username",property = "userName"),@Result(column = "address",property = "userAddress"),@Result(column = "sex",property = "userSex"),@Result(column = "birthday",property = "userBirthday"),@Result(property = "accounts",column = "id",many=@Many(select = "com.jindashen.dao.AccountDao.findAccountByUid",fetchType = FetchType.LAZY))})List<User> findAll();/*** @Description: 通过id查询用户* @Param: [id]* @return: com.jindashen.domain.User* @Author: Mr.King* @Date: 2021/9/3*/@Select(value = "select * from user where id=#{id}")@ResultMap(value={"userMap"})User findUserById(Integer id);/*** @Description: 根据用户名进行模糊查询* @Param: [username]* @return: java.util.List<com.jindashen.domain.User>* @Author: Mr.King* @Date: 2021/9/3*/@Select(value = "select * from user where username like #{username}")@ResultMap(value={"userMap"})List<User> findUserByName(String username);}
测试代码:
/*** @Description: 查询所有* @Param: []* @return: void* @Author: Mr.King* @Date: 2021/9/3*/@Testpublic void testFindAll(){List<User> users = userDao.findAll();for (User user : users) {System.out.println("--------用户信息----------");System.out.println(user);System.out.println("--------账户信息----------");System.out.println(user.getAccounts());}}
测试结果:
2021-09-04 13:11:47,450 131 [ main] DEBUG .apache.ibatis.io.ResolverUtil - Checking to see if class com.jindashen.dao.AccountDao matches criteria [is assignable to Object]
2021-09-04 13:11:47,451 132 [ main] DEBUG .apache.ibatis.io.ResolverUtil - Checking to see if class com.jindashen.dao.UserDao matches criteria [is assignable to Object]
2021-09-04 13:11:47,487 168 [ main] DEBUG com.jindashen.dao.UserDao - Cache Hit Ratio [com.jindashen.dao.UserDao]: 0.0
2021-09-04 13:11:47,487 168 [ main] DEBUG ansaction.jdbc.JdbcTransaction - Opening JDBC Connection
2021-09-04 13:11:47,657 338 [ main] DEBUG source.pooled.PooledDataSource - Created connection 1439394198.
2021-09-04 13:11:47,658 339 [ main] DEBUG .jindashen.dao.UserDao.findAll - ==> Preparing: select * from user
2021-09-04 13:11:47,665 346 [ main] DEBUG .jindashen.dao.UserDao.findAll - ==> Parameters:
2021-09-04 13:11:47,712 393 [ main] DEBUG .jindashen.dao.UserDao.findAll - <== Total: 9
--------用户信息----------
2021-09-04 13:11:47,712 393 [ main] DEBUG ao.AccountDao.findAccountByUid - ==> Preparing: select * from account where uid=?
2021-09-04 13:11:47,712 393 [ main] DEBUG ao.AccountDao.findAccountByUid - ==> Parameters: 41(Integer)
2021-09-04 13:11:47,712 393 [ main] DEBUG ao.AccountDao.findAccountByUid - <== Total: 2
User{userId=41, userName='Tonny', userAddress='USA', userSex='男', userBirthday=Tue Feb 27 17:47:08 CST 2018}
--------账户信息----------
[Account{id=1, uid=41, money=1000.0}, Account{id=3, uid=41, money=2000.0}]
--------用户信息----------
2021-09-04 13:11:47,712 393 [ main] DEBUG ao.AccountDao.findAccountByUid - ==> Preparing: select * from account where uid=?
2021-09-04 13:11:47,727 408 [ main] DEBUG ao.AccountDao.findAccountByUid - ==> Parameters: 42(Integer)
2021-09-04 13:11:47,727 408 [ main] DEBUG ao.AccountDao.findAccountByUid - <== Total: 0
User{userId=42, userName='小二王', userAddress='China', userSex='女', userBirthday=Fri Mar 02 15:09:37 CST 2018}
--------账户信息----------
[]
--------用户信息----------
2021-09-04 13:11:47,727 408 [ main] DEBUG ao.AccountDao.findAccountByUid - ==> Preparing: select * from account where uid=?
2021-09-04 13:11:47,727 408 [ main] DEBUG ao.AccountDao.findAccountByUid - ==> Parameters: 43(Integer)
2021-09-04 13:11:47,727 408 [ main] DEBUG ao.AccountDao.findAccountByUid - <== Total: 0
User{userId=43, userName='小二王', userAddress='China', userSex='女', userBirthday=Sun Mar 04 11:34:34 CST 2018}
--------账户信息----------
[]
--------用户信息----------
2021-09-04 13:11:47,727 408 [ main] DEBUG ao.AccountDao.findAccountByUid - ==> Preparing: select * from account where uid=?
2021-09-04 13:11:47,727 408 [ main] DEBUG ao.AccountDao.findAccountByUid - ==> Parameters: 45(Integer)
2021-09-04 13:11:47,727 408 [ main] DEBUG ao.AccountDao.findAccountByUid - <== Total: 1
User{userId=45, userName='金大神', userAddress='China', userSex='男', userBirthday=Sun Mar 04 12:04:06 CST 2018}
--------账户信息----------
[Account{id=2, uid=45, money=1000.0}]
--------用户信息----------
2021-09-04 13:11:47,727 408 [ main] DEBUG ao.AccountDao.findAccountByUid - ==> Preparing: select * from account where uid=?
2021-09-04 13:11:47,727 408 [ main] DEBUG ao.AccountDao.findAccountByUid - ==> Parameters: 46(Integer)
2021-09-04 13:11:47,727 408 [ main] DEBUG ao.AccountDao.findAccountByUid - <== Total: 0
User{userId=46, userName='老王', userAddress='China', userSex='男', userBirthday=Wed Mar 07 17:37:26 CST 2018}
--------账户信息----------
[]
--------用户信息----------
2021-09-04 13:11:47,727 408 [ main] DEBUG ao.AccountDao.findAccountByUid - ==> Preparing: select * from account where uid=?
2021-09-04 13:11:47,727 408 [ main] DEBUG ao.AccountDao.findAccountByUid - ==> Parameters: 48(Integer)
2021-09-04 13:11:47,727 408 [ main] DEBUG ao.AccountDao.findAccountByUid - <== Total: 0
User{userId=48, userName='海绵宝宝', userAddress='China', userSex='女', userBirthday=Thu Mar 08 11:44:00 CST 2018}
--------账户信息----------
[]
--------用户信息----------
2021-09-04 13:11:47,727 408 [ main] DEBUG ao.AccountDao.findAccountByUid - ==> Preparing: select * from account where uid=?
2021-09-04 13:11:47,727 408 [ main] DEBUG ao.AccountDao.findAccountByUid - ==> Parameters: 59(Integer)
2021-09-04 13:11:47,727 408 [ main] DEBUG ao.AccountDao.findAccountByUid - <== Total: 0
User{userId=59, userName='Anny', userAddress='USA', userSex='女', userBirthday=Tue Aug 31 19:40:44 CST 2021}
--------账户信息----------
[]
--------用户信息----------
2021-09-04 13:11:47,727 408 [ main] DEBUG ao.AccountDao.findAccountByUid - ==> Preparing: select * from account where uid=?
2021-09-04 13:11:47,727 408 [ main] DEBUG ao.AccountDao.findAccountByUid - ==> Parameters: 62(Integer)
2021-09-04 13:11:47,727 408 [ main] DEBUG ao.AccountDao.findAccountByUid - <== Total: 0
User{userId=62, userName='Tom', userAddress='USA', userSex='男', userBirthday=Tue Aug 31 20:16:32 CST 2021}
--------账户信息----------
[]
--------用户信息----------
2021-09-04 13:11:47,727 408 [ main] DEBUG ao.AccountDao.findAccountByUid - ==> Preparing: select * from account where uid=?
2021-09-04 13:11:47,727 408 [ main] DEBUG ao.AccountDao.findAccountByUid - ==> Parameters: 65(Integer)
2021-09-04 13:11:47,727 408 [ main] DEBUG ao.AccountDao.findAccountByUid - <== Total: 0
User{userId=65, userName='Ben', userAddress='USA', userSex='男', userBirthday=Fri Sep 03 18:51:20 CST 2021}
--------账户信息----------
[]
2021-09-04 13:11:47,727 408 [ main] DEBUG ansaction.jdbc.JdbcTransaction - Closing JDBC Connection [com.mysql.jdbc.JDBC4Connection@55cb6996]
2021-09-04 13:11:47,727 408 [ main] DEBUG source.pooled.PooledDataSource - Returned connection 1439394198 to pool.
附录
UserDao接口
package com.jindashen.dao;import com.jindashen.domian.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;/*** @program: annotation* @description:* @author: Mr.King* @create: 2021-09-04 10:55**/public interface UserDao {/*** @Description: 查询所有用户* @Param: []* @return: java.util.List<com.jindashen.domain.User>* @Author: Mr.King* @Date: 2021/9/4*/@Select(value="select * from user")List<User> findAll();/*** @Description: 保存用户* @Param: [user]* @return: void* @Author: Mr.King* @Date: 2021/9/4*/@Insert(value = "insert into user(username,address,sex,birthday) values(#{username},#{address},#{sex},#{birthday})")void saveUser(User user);/*** @Description: 更新用户信息* @Param: [user]* @return: void* @Author: Mr.King* @Date: 2021/9/4*/@Update(value = "update user set username=#{username},sex=#{sex},birthday=#{birthday},address=#{address} where id=#{id}")void updateUser(User user);/*** @Description: 删除用户信息* @Param: [id]* @return: void* @Author: Mr.King* @Date: 2021/9/4*/@Delete(value="delete from user where id=#{id}")void deleteUserById(Integer id);/*** @Description: 通过id查询用户* @Param: [id]* @return: com.jindashen.domain.User* @Author: Mr.King* @Date: 2021/9/4*/@Select(value = "select * from user where id=#{id}")User findUserById(Integer id);/*** @Description: 根据用户名进行模糊查询* @Param: [username]* @return: java.util.List<com.jindashen.domain.User>* @Author: Mr.King* @Date: 2021/9/4*/@Select(value = "select * from user where username like #{username}")List<User> findUserByName(String username);/*** @Description: 查询用户数量* @Param: []* @return: int* @Author: Mr.King* @Date: 2021/9/4*/@Select(value = "select count(*) from user")int findTotalUser();
}
MybatisTest.java
package com.jindashen.test;import com.jindashen.dao.UserDao;
import com.jindashen.domian.User;
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 java.io.InputStream;
import java.util.Date;
import java.util.List;/*** @program: annotation* @description:* @author: Mr.King* @create: 2021-09-04 10:57**/public class MybatisTest {private InputStream in;private SqlSession sqlSession;private UserDao userDao;SqlSessionFactory factory;/*** @Description: 初始化,用于在测试方法执行之前执行* @Param: []* @return: void* @Author: Mr.Jin* @Date: 2021/8/7*/@Beforepublic void init() throws Exception {//读取配置文件,生成输入流in = Resources.getResourceAsStream("SqlMapConfig.xml");//读取SqlSessionFactoryfactory = new SqlSessionFactoryBuilder().build(in);//获取SqlSession对象sqlSession = factory.openSession(true);//获取dao的代理对象userDao = sqlSession.getMapper(UserDao.class);}/*** @Description: 释放,用于在测试方法执行之后执行* @Param: []* @return: void* @Author: Mr.Jin* @Date: 2021/8/7*/@Afterpublic void destory() throws Exception {//释放资源sqlSession.close();in.close();}/*** @Description: 查询所有* @Param: []* @return: void* @Author: Mr.King* @Date: 2021/9/4*/@Testpublic void testFindAll(){List<User> users = userDao.findAll();for (User user : users) {System.out.println(user);}}/*** @Description: 保存用户信息* @Param: []* @return: void* @Author: Mr.King* @Date: 2021/9/4*/@Testpublic void testInsert(){User user = new User();user.setUsername("Ben");user.setAddress("USA");user.setSex("男");user.setBirthday(new Date());userDao.saveUser(user);}/*** @Description: 更新用户信息* @Param: []* @return: void* @Author: Mr.King* @Date: 2021/9/4*/@Testpublic void testUpdate(){User user = new User();user.setId(66);user.setUsername("Ben1");user.setAddress("USA1");user.setSex("男");user.setBirthday(new Date());userDao.updateUser(user);}/*** @Description: 删除用户信息* @Param: []* @return: void* @Author: Mr.King* @Date: 2021/9/4*/@Testpublic void testDelete(){userDao.deleteUserById(66);}/*** @Description: 测试通过id查询用户* @Param: []* @return: void* @Author: Mr.King* @Date: 2021/9/4*/@Testpublic void testFindUserById(){User user = userDao.findUserById(65);System.out.println(user);}/*** @Description: 测试根据用户名进行模糊查询* @Param: []* @return: void* @Author: Mr.King* @Date: 2021/9/4*/@Testpublic void testFindUserByName(){List<User> users = userDao.findUserByName("%王%");for (User user : users) {System.out.println(user);}}/*** @Description: 测试查询用户数量* @Param: []* @return: void* @Author: Mr.King* @Date: 2021/9/4*/@Testpublic void testFindTotalUser(){Integer num = userDao.findTotalUser();System.out.println(num);}
}
Mybatis注解开发笔记相关推荐
- MyBatis-学习笔记12【12.Mybatis注解开发】
Java后端 学习路线 笔记汇总表[黑马程序员] MyBatis-学习笔记01[01.Mybatis课程介绍及环境搭建][day01] MyBatis-学习笔记02[02.Mybatis入门案例] M ...
- Mybatis 注解开发 + 动态SQL
Hello 大家好我是橙子同学,今天分享注解Mybatis注解开发+动态sql 目录 每文一铺垫(今天有小插曲哦) 注解开发 添加 @Insert 删除 @Delete 查询 @Select 修改 @ ...
- Mybatis注解开发(一对一)
其他代码访问:Mybatis注解开发基础操作 1.添加OrderMapper接口 public interface OrderMapper {// @Select("select *,o.i ...
- java day56【 Mybatis 延迟加载策略 、 Mybatis 缓存、Mybatis 注解开发 】
第1章 Mybatis 延迟加载策略 1.1 何为延迟加载? 1.2 实现需求 1.3 使用 assocation 实现延迟加载 1.3.1 账户的持久层 DAO 接口 1.3.2 账户的持久层映射文 ...
- Mybatis注解开发指北
Mybatis注解开发指北 目录 文章目录 Mybatis注解开发指北 @[toc] 0. Mybatis注解开发步骤 1. 导入相关配置文件 2. 配置数据库连接 3. 创建数据库对应的实体类(en ...
- Mybatis注解开发出现Type interface Mapper.StudentMapper is not known to the MapperRegistry异常解决办法
Mybatis注解开发出现Type interface Mapper.StudentMapper is not known to the MapperRegistry异常解决办法 在核心配置文件中,配 ...
- mybatis注解开发动态sql
mybatis注解开发动态sql 本篇来讲一下如何使用mybatis注解模式中的动态sql 先来讲一下什么是动态sql 在我们实际开发的时候可能会出现很多方法需要一条很相似的sql语句来进行增删改查, ...
- Mybatis注解开发(超详细)
Mybatis注解开发 mybatis的常用注解 使用 Mybatis 注解实现基本 CRUD 项目目录结构 编写实体类 使用注解方式开发持久层接口 编写 SqlMapConfig.xml 配置文件 ...
- Java神鬼莫测之MyBatis注解开发之动态SQL语句(六)
1.Mybatis注解开发之动态SQL语句 背景:使用mybatis的注解开发动态Sql会比较麻烦, 很不方便, 所以不太推荐使用,该文章以查询作为案例,演示动态sql语句. 注意:Mybatis的动 ...
最新文章
- MySQL中文参考手册-- 常用查询的例子
- C++自学笔记_文本查询程序_《C++ Primer》
- Angular6错误 Service: No provider for Renderer2
- Spring数据和Redis
- ZZULIOJ 1074:百钱买百鸡
- 《那些年啊,那些事——一个程序员的奋斗史》——54
- python在电脑下载-Windows下下载及安装numpy、pandas及简单应用
- 04 grep正则表达式与shellscipt脚本编程
- android RecyclerView实战
- 火狐 firefox proxy moz=proxy:// 407错误 解决办法
- 硬盘SMART检测参数详解
- 以太网与工业以太网的区别
- 嵌入式系统测试教学实训平台系统情况
- HCNE之RIP协议总结
- PHP-SDK实现支付宝 付款码支付、刷脸支付
- 当路町-网络下载应用系列之三-认识磁力链接Magnet URL
- 私有文件服务器,文件服务器与私有云盘
- guided filter(导向滤波)导读
- 互联网时代产品研发的思考
- OpenMeetings(3)----启动顺序解析
热门文章
- 我的世界java版钻石剑附魔_我的世界钻石剑怎么附魔 钻石剑附魔100级指令
- 几种Web服务器比较-(Apache、IIS、Lighttpd、Nginx、LiteSpeed、Zeus
- Unity快速入门之四 - Unity模型动画相关
- 出入库管理系统-精致版
- c语言快排过程,快速排序(快排)C语言实现
- android m是什么版本号,Android m是什么版本
- matlab gui输入函数,紧急求助!关于matlab中GUI用户图形界面通过edit输入调用函数问题!...
- 由浅入深 学习 Android Binder(十一) binder线程池
- cad绘制正八边形_软件CAD | 各种“线”工具
- 抽取modelnet40_ply_hdf5_2048数据集的子类集制作h5点云