MyBatis的注解式开发 一、准备开发环境 1.添加依赖 2.jdbc.properties 3.mybatis-config.xml 4.Article实体类 5.SqlSessionUtil工具类 二、Insert 三、Delete 四、Update 五、Select
mybatis 中也提供了注解式开发⽅式,采⽤注解可以减少 Sql 映射⽂件的配置。 使⽤注解式开发的话,sql语句是写在java程序中的,这种⽅式也会给sql语句的维护带来成本。 官⽅是这么说的:使⽤注解来映射简单语句会使代码显得更加简洁,但对于稍微复杂⼀点的语句,Java 注解不仅⼒不从⼼,还会让你本就复杂的 SQL 语句更加混乱不堪。 因此,如果你需要做⼀些很复杂的操作,最好⽤ XML 来映射语句。 总结:一般对单表的 CRUD 可以采用注解的方式开发。
一、准备开发环境
1.添加依赖
<?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> coml.gdb</ groupId> < artifactId> mybatis-annotation</ artifactId> < version> 1.0-SNAPSHOT</ version> < properties> < maven.compiler.source> 17</ maven.compiler.source> < maven.compiler.target> 17</ maven.compiler.target> < project.build.sourceEncoding> UTF-8</ project.build.sourceEncoding> </ properties> < dependencies> < dependency> < groupId> org.mybatis</ groupId> < artifactId> mybatis</ artifactId> < version> 3.5.14</ version> </ dependency> < dependency> < groupId> mysql</ groupId> < artifactId> mysql-connector-java</ artifactId> < version> 8.0.33</ version> </ dependency> < dependency> < groupId> junit</ groupId> < artifactId> junit</ artifactId> < version> 4.13.2</ version> < scope> test</ scope> </ dependency> </ dependencies>
</ project>
2.jdbc.properties
jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/自己的数据库名字
jdbc.username=用户名
jdbc.password=密码
3.mybatis-config.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 = " jdbc.properties" > </ properties> < settings> < setting name = " logImpl" value = " STDOUT_LOGGING" /> </ settings> < environments default = " development" > < environment id = " development" > < transactionManager type = " JDBC" /> < 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> < mappers> < package name = " com.gdb.annotation.mapper" /> </ mappers> </ configuration>
4.Article实体类
package com. gdb. annotation. pojo ; import java. time. LocalDateTime ; public class Article { private Integer id; private Integer userId; private String summary; private String title; private Integer readCount; private LocalDateTime createTime; private LocalDateTime updateTime; @Override public String toString ( ) { return "Article{" + "id=" + id + ", userId=" + userId + ", summary='" + summary + '\'' + ", title='" + title + '\'' + ", readCount=" + readCount + ", createTime=" + createTime + ", updateTime=" + updateTime + '}' ; } public Article ( ) { } public Article ( Integer id, Integer userId, String summary, String title, Integer readCount, LocalDateTime createTime, LocalDateTime updateTime) { this . id = id; this . userId = userId; this . summary = summary; this . title = title; this . readCount = readCount; this . createTime = createTime; this . updateTime = updateTime; } public Integer getId ( ) { return id; } public void setId ( Integer id) { this . id = id; } public Integer getUserId ( ) { return userId; } public void setUserId ( Integer userId) { this . userId = userId; } public String getSummary ( ) { return summary; } public void setSummary ( String summary) { this . summary = summary; } public String getTitle ( ) { return title; } public void setTitle ( String title) { this . title = title; } public Integer getReadCount ( ) { return readCount; } public void setReadCount ( Integer readCount) { this . readCount = readCount; } public LocalDateTime getCreateTime ( ) { return createTime; } public void setCreateTime ( LocalDateTime createTime) { this . createTime = createTime; } public LocalDateTime getUpdateTime ( ) { return updateTime; } public void setUpdateTime ( LocalDateTime updateTime) { this . updateTime = updateTime; }
}
5.SqlSessionUtil工具类
package com. gdb. annotation. utils ; import org. apache. ibatis. io. Resources ;
import org. apache. ibatis. session. SqlSession ;
import org. apache. ibatis. session. SqlSessionFactory ;
import org. apache. ibatis. session. SqlSessionFactoryBuilder ; public class SqlSessionUtil { private static SqlSessionFactory sqlSessionFactory; static { try { SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder ( ) ; sqlSessionFactory = sqlSessionFactoryBuilder. build ( Resources . getResourceAsStream ( "mybatis-config.xml" ) ) ; } catch ( Exception e) { e. printStackTrace ( ) ; } } public static SqlSession openSession ( ) { return sqlSessionFactory. openSession ( ) ; }
}
二、Insert
package com. gdb. annotation. mapper ; import com. gdb. annotation. pojo. Article ;
import org. apache. ibatis. annotations. Insert ; public interface ArticleMapper { @Insert ( "insert into article values (null, #{userId}, #{title}, #{summary}, #{readCount}, #{createTime}, #{updateTime})" ) int insert ( Article article) ; }
Annotation.InsertAnnotationtest
package com. gdb. annotationTest ; import com. gdb. annotation. mapper. ArticleMapper ;
import com. gdb. annotation. pojo. Article ;
import com. gdb. annotation. utils. MybatisUtils ;
import org. apache. ibatis. session. SqlSession ;
import org. junit. Test ; import java. time. LocalDateTime ; public class Annotation { @Test public void insertAnnotationTest ( ) { SqlSession sqlSession = MybatisUtils . openSession ( ) ; ArticleMapper mapper = sqlSession. getMapper ( ArticleMapper . class ) ; Article article = new Article ( null , 12346 , "springboot 配置文件" , "外部化配置文件" , 12346 , LocalDateTime . now ( ) , LocalDateTime . now ( ) ) ; int count = mapper. insert ( article) ; System . out. println ( "插入的记录条数 ===> " + count) ; sqlSession. commit ( ) ; sqlSession. close ( ) ; }
}
三、Delete
@Delete ( "delete from article where id = #{id}" )
int delete ( int id) ;
Annotation.deleteAnnotationTest
@Test
public void deleteAnnotationTest ( ) { SqlSession sqlSession = MybatisUtils . openSession ( ) ; ArticleMapper mapper = sqlSession. getMapper ( ArticleMapper . class ) ; int count = mapper. delete ( 13 ) ; System . out. println ( "删除的记录条数 ===> " + count) ; sqlSession. commit ( ) ; sqlSession. close ( ) ; }
四、Update
@Update ( "update article set user_id=#{userId}, title=#{title} where id=#{id}" )
int update ( Article article) ;
Annotation.updateAnnotationTest
@Test
public void updateAnnotationTest ( ) { SqlSession sqlSession = MybatisUtils . openSession ( ) ; ArticleMapper mapper = sqlSession. getMapper ( ArticleMapper . class ) ; Article article = new Article ( 19 , 12346 , "springboot 配置文件" , "外部化配置文件" , 12346 , LocalDateTime . now ( ) , LocalDateTime . now ( ) ) ; int count = mapper. update ( article) ; System . out. println ( "插入的记录条数 ===> " + count) ; sqlSession. commit ( ) ; sqlSession. close ( ) ;
}
五、Select
@Select ( "select * from Article where id = #{id}" )
@Results ( { @Result ( property = "userId" , column = "user_id" ) , @Result ( property = "readCount" , column = "read_count" ) , @Result ( property = "createTime" , column = "create_time" ) , @Result ( property = "updateTime" , column = "update_time" )
} )
Article selectById ( int id) ;
Annotation.seleteAnnotationTest
@Test
public void selectAnnotationTest ( ) { SqlSession sqlSession = MybatisUtils . openSession ( ) ; ArticleMapper mapper = sqlSession. getMapper ( ArticleMapper . class ) ; Article article = mapper. selectById ( 1 ) ; System . out. println ( article) ; sqlSession. commit ( ) ; sqlSession. close ( ) ;
}
注意:如果不想使用 @Results 注解的话可以在mybatis-config.xml 配置文件中添加如下配置。
< settings> < setting name = " mapUnderscoreToCamelCase" value = " true" /> </ settings>