1、MyBatis的常用注解
这几年来注解开发越来越流行,Mybatis也可以使用注解开发方式,这样我们就可以减少编写Mapper 映射文件了。
- @Insert:实现新增
- @Update:实现更新
- @Delete:实现删除
- @Select:实现查询
- @Result:实现结果集封装
- @Results:可以与@Result 一起使用,封装多个结果集
- @One:实现一对一结果集封装
- @Many:实现一对多结果集封装
2、MyBatis注解方式的增删改查
修改MyBatis的核心配置文件,我们使用了注解替代的映射文件,所以我们只需要加载使用了注解的Mapper接口即可。
<!--加载映射关系-->
<mappers>
<!--指定接口所在的包-->
<package name="com.xmp.mapper"></package>
</mappers>
- 增
"insert into user values(#{id},#{username},#{password},#{birthday})") (publicvoidsave(Useruser);
- 删
"update user set username=#{username},password=#{password} where id=#{id}") (publicvoidupdate(Useruser);
- 改
"delete from user where id=#{id}") (publicvoiddelete(intid);
- 查
"select * from user where id=#{id}") (publicUserfindById(intid); "select * from user") (publicList<User>findAll();
3、MyBatis的注解实现复杂映射
实现复杂关系映射之前我们可以在映射文件中通过配置来实现,使用注解开发后,我们可以使用@Results注解 ,@Result注解,@One注解,@Many注解组合完成复杂关系的配置。
注解 | 说明 |
@Results | 代替的是标签该注解中可以使用单个@Result注解,也可以使用@Result集 合。使用格式:@Results({@Result(),@Result()})或@Results(@Result()) |
@Resut | 代替了标签和标签 @Result中属性介绍: column:数据库的列名 property:需要装配的属性名 one:需要使用的@One 注解(@Result(one=@One)())) many:需要使用的@Many 注解(@Result(many=@many)())) |
@One (一对一) | 代替了 标签,是多表查询的关键,在注解中用来指定子查询返回单一对象。 @One注解属性介绍: select: 指定用来多表查询的 sqlmapper 使用格式:@Result(column=" ",property="",one=@One(select="")) |
@Many (多对一) | 代替了标签, 是是多表查询的关键,在注解中用来指定子查询返回对象集合。 使用格式:@Result(property="",column="",many=@Many(select="")) |
4、Mybatis注解开发步骤
1.导入maven依赖:
<dependencies>
<!-- https://mvnrepository.com/artifact/org.objectweb.asm/org.objectweb.asm -->
<dependency>
<groupId>org.objectweb.asm</groupId>
<artifactId>org.objectweb.asm</artifactId>
<version>3.3.1.v201105211655</version>
</dependency>
<!-- https://mvnrepository.com/artifact/cglib/cglib -->
<dependency>
<groupId>cglib</groupId>
<artifactId>cglib</artifactId>
<version>3.2.8</version>
</dependency>
<!-- https://mvnrepository.com/artifact/commons-logging/commons-logging -->
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/net.sf.ehcache/ehcache-core -->
<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache-core</artifactId>
<version>2.6.11</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.javassist/javassist -->
<dependency>
<groupId>org.javassist</groupId>
<artifactId>javassist</artifactId>
<version>3.23.1-GA</version>
</dependency>
<!-- https://mvnrepository.com/artifact/junit/junit -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/log4j/log4j -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.logging.log4j/log4j-api -->
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>2.11.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.logging.log4j/log4j-core -->
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.11.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.6</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.mybatis.caches/mybatis-ehcache -->
<dependency>
<groupId>org.mybatis.caches</groupId>
<artifactId>mybatis-ehcache</artifactId>
<version>1.1.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.12</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-log4j12 -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.8.0-beta2</version>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-api -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.8.0-beta2</version>
</dependency>
</dependencies>
2.数据库信息:
jdbc.driver=com.mysql.jdbc.Driverjdbc.url=jdbc:mysql://localhost:3306/mybatisjdbc.username=rootjdbc.passwords=root
3.编写日志配置文件:
##将等级为INFO的日志信息输出到stdout和R这两个目的
log4j.rootCategory=INFO, stdout , R
#日志输出到控制台-- log4j.appender.stdout=org.apache.log4j.ConsoleAppender
#日志布局样式-自定义样式
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
#日志样式
log4j.appender.stdout.layout.ConversionPattern=[QC] %p [%t] %C.%M(%L) | %m%n
##日志到每天一个日志文件
log4j.appender.R=org.apache.log4j.DailyRollingFileAppender
##日志输出地址
log4j.appender.R.File=D:\\my.log
#日志布局样式-自定义样式
log4j.appender.R.layout=org.apache.log4j.PatternLayout
#日志样式
1log4j.appender.R.layout.ConversionPattern=%d-[TS] %p %t %c - %m%n
##下面是指定具体的包下面的所有日志的级别
log4j.logger.com.neusoft=DEBUG
log4j.logger.com.opensymphony.oscache=ERROR
log4j.logger.net.sf.navigator=ERROR
log4j.logger.org.apache.commons=ERROR
log4j.logger.org.apache.struts=WARN
log4j.logger.org.displaytag=ERROR
log4j.logger.org.springframework=DEBUG
log4j.logger.com.ibatis.db=WARN
log4j.logger.org.apache.velocity=FATAL
4.编写配置文件:
SqlMapConfig.xml:
<?xmlversion="1.0"encoding="UTF-8"?><!DOCTYPEconfigurationPUBLIC"-//mybatis.org//DTD Config 3.0//EN""http://mybatis.org/dtd/mybatis-3-config.dtd"><configuration><propertiesresource="db.properties"></properties><settings><settingname="lazyLoadingEnabled"value="true"/><settingname="aggressiveLazyLoading"value="false"/><settingname="cacheEnabled"value="true"></setting></settings><typeAliases><!--别名--><!--<typeAliastype="com.xmp.entity.User"alias="user"></typeAlias>--><packagename="com.xmp..pojo"></package></typeAliases><environmentsdefault="development"><environmentid="development"><transactionManagertype="JDBC"></transactionManager><dataSourcetype="POOLED"><propertyname="driver"value="${jdbc.driver}"></property><propertyname="url"value="${jdbc.url}"></property><propertyname="username"value="${jdbc.username}"></property><propertyname="password"value="${jdbc.password}"></property></dataSource></environment></environments><mappers><!--<mapperresource="sqlmap/User.xml"></mapper>--><!--<mapperresource="mapper/UserMapper.xml"></mapper>--><!--Mapper接口和映射文件必须在同一文件夹下遵循规范<mapperclass="com.xmp..mapper.UserMapper"></mapper>--><!--Mapper接口的包名,自动扫描。遵循规范<packagename=""></package>--><packagename="com.xmp.mapper"></package><packagename="com.xmp.pojo"></package></mappers></configuration>
5.编写pojo类和Mapper接口:
publicinterfaceUserMapper { "select * from user where id=#{id}") (publicUsergetUserById(Integerid); "delete from user where id=#{id}") (publicvoiddeleteUserById(Integerid); "insert user(id,username,birthday,sex,address) value(#{id},#{username},#{birthday},#{sex},#{address})") (publicvoidaddUser(Useruser); "update user set id=#{id},username=#{username},birthday=#{birthday},sex=#{sex},address=#{address} where id=#{id}") (publicvoidupdateUser(Useruser); }
public class User {
private int id;
private String username;
private Date birthday;
private Integer sex;
private String address;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public Date getBirthday(Date date) {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public Integer getSex() {
return sex;
}
public void setSex(Integer 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 + '\'' +
", birthday=" + birthday +
", sex=" + sex +
", address='" + address + '\'' +
'}';
}
}
6.编写测试类:
public class UserMapperTest {
SqlSessionFactory sqlSessionFactory;
@Before
public void setUp() throws Exception {
InputStream resourceAsStream = Resources.getResourceAsStream("SqlMapConfig.xml");
//初始化mybatis,创建SqlSessionFactory类的实例
sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
}
publicvoidgetUserById() { SqlSessionsqlSession=sqlSessionFactory.openSession(); UserMapperuserMapper=sqlSession.getMapper(UserMapper.class); UseruserById=userMapper.getUserById(10); System.out.println("Message="+userById); }
publicvoiddeleteUserById() { SqlSessionsqlSession=sqlSessionFactory.openSession(); UserMapperuserMapper=sqlSession.getMapper(UserMapper.class); userMapper.deleteUserById(26); }
publicvoidaddUser() { SqlSessionsqlSession=sqlSessionFactory.openSession(); UserMapperuserMapper=sqlSession.getMapper(UserMapper.class); Useruser=newUser(); user.setId(30); user.setUsername("xmp"); user.setBirthday(newDate()); user.setAddress("SH"); userMapper.addUser(user); sqlSession.commit(); }
publicvoidupdateUser() { SqlSessionsqlSession=sqlSessionFactory.openSession(); UserMapperuserMapper=sqlSession.getMapper(UserMapper.class); UseruserById=userMapper.getUserById(1); userById.setBirthday(newDate()); userById.setAddress("广西柳州"); userMapper.updateUser(userById); sqlSession.commit(); }
}