Spring Boot 集成mybatis gradle
mybatis 注解方式
mybatis xml方式
分页查询 pagehelper
mybatis 注解方式
第一步:引入依赖包: build.gradle
buildscript {
ext {
springBootVersion = '1.5.8.RELEASE'
}
repositories {
mavenCentral()
}
dependencies {
classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
}
}
apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'org.springframework.boot'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = 1.8
repositories {
mavenCentral()
}
dependencies {
compile('org.springframework.boot:spring-boot-starter')
testCompile('org.springframework.boot:spring-boot-starter-test')
compile 'mysql:mysql-connector-java'
//配置mybatis 数据源 //一定要加版本号1.3.0或者更高的版本号
compile("org.mybatis.spring.boot:mybatis-spring-boot-starter:1.3.0")
testCompile('org.mybatis.spring.boot:mybatis-spring-boot-starter-test:1.3.0')
//使用 Controller 的时候需要引入 web 包
compile('org.springframework.boot:spring-boot-starter-web')
}
第二步:数据库连接配置 application.yml
spring:
datasource:
url: jdbc:mysql://localhost:3306/test?characterEncoding=utf8
username: root
password: root
第三步:在Springboot的启动主类中增加包扫描 Mapper 文件,也可以在 xml 文件中配置,以下使用注解。
@SpringBootApplication
@MapperScan("com.example.demo.dao.mapper")
public class App {
public static void main(String[] args) {
SpringApplication.run(App.class, args);
}
}
第四步:写 Mapper 接口,使用 mybatis 的注解
public interface UserMapper {
@Select("select * from person where id = #{id}")
Person findByID(Integer id);
//返回的Integer值是变化的行数,@Options()会填充到实体 person 中。
@Insert("insert into person(name, age) values(#{name}, #{age})")
@Options(useGeneratedKeys = true, keyProperty = "id")
Integer addPerson(Person person);
// @Insert("insert into person(name, age) values(#{name}, #{age})")
// Integer addPerson(@Param("name") String name, @Param("age") Integer age);
@Update("update person set name = #{name}, age = #{age} where id = #{id}")
Integer updatePerson(@Param("name") String name, @Param("age") Integer age, @Param("id") int id);
@Delete("delete from person where id = #{id}")
Integer deletePerson(Integer id);
@Select("select * from person")
List<Person> findAllPage();
}
mybatis xml方式
第一步:引入依赖包: build.gradle
buildscript {
ext {
springBootVersion = '1.5.4.RELEASE'
}
repositories {
mavenCentral()
}
dependencies {
classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
}
}
apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'org.springframework.boot'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = 1.8
repositories {
mavenCentral()
}
dependencies {
compile('org.springframework.boot:spring-boot-starter')
testCompile('org.springframework.boot:spring-boot-starter-test')
compile 'mysql:mysql-connector-java'
//配置mybatis 数据源
compile("org.mybatis.spring.boot:mybatis-spring-boot-starter:1.3.0")
testCompile('org.mybatis.spring.boot:mybatis-spring-boot-starter-test:1.3.0')
//使用 Controller 的时候需要引入 web 包
compile('org.springframework.boot:spring-boot-starter-web')
}
第二步:数据库连接配置 application.yml
spring:
datasource:
url: jdbc:mysql://localhost:3306/test?characterEncoding=utf8
username: root
password: root
mybatis:
type-aliases-package: org.larry.springboot.entity
mapper-locations: classpath:mapper/**/*.xml
check-config-location: true
第三步:在Springboot的启动主类中配置包扫描 Mapper 文件 Application.java
@SpringBootApplication
@MapperScan("com.example.demo.mapper")
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
或者直接在Mapper类上面添加注解@Mapper,建议使用上面那种,不然每个mapper加个注解也挺麻烦的
第四步:测试代码
创建model 和 Mapper 文件用于测试,但是可以使用 generator 自动生成。
public class User {
private Integer id;
private String name;
public User(Integer id, String name) {
this.id = id;
this.name = name;
}
public User() {
super();
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name == null ? null : name.trim();
}
}
public interface UserMapper {
long countByExample(UserExample example);
int deleteByExample(UserExample example);
int deleteByPrimaryKey(Integer id);
int insert(User record);
int insertSelective(User record);
List<User> selectByExample(UserExample example);
User selectByPrimaryKey(Integer id);
int updateByExampleSelective(@Param("record") User record, @Param("example") UserExample example);
int updateByExample(@Param("record") User record, @Param("example") UserExample example);
int updateByPrimaryKeySelective(User record);
int updateByPrimaryKey(User record);
@Select("select * from user")
List<User> findAll();
}
@RestController
public class UserContorller {
@Autowired
private UserMapper userMapper;
@RequestMapping("/insert")
public User insertUser() {
User user = new User(null, "inke");
userMapper.insert(user);
return user;
}
@RequestMapping("/findAll")
public List<User> findAll() {
return userMapper.findAll();
}
}
Mybatis 分页查询pagehelper
第一步:引入依赖包: build.gradle
dependencies {
compile('org.springframework.boot:spring-boot-starter')
testCompile('org.springframework.boot:spring-boot-starter-test')
compile 'org.springframework.boot:spring-boot-devtools'
compile 'mysql:mysql-connector-java'
//配置mybatis 数据源
compile("org.mybatis.spring.boot:mybatis-spring-boot-starter:1.3.0")
testCompile('org.mybatis.spring.boot:mybatis-spring-boot-starter-test:1.3.0')
//pagehelper
compile("com.github.pagehelper:pagehelper-spring-boot-starter:1.1.1")
//mapper 使用 xml 的 mybatis 方式,需要引入下面的包,不然 dev-tools 会报错
//compile("tk.mybatis:mapper-spring-boot-starter:1.1.1")
}
第二步:数据库连接配置 application.yml
server:
port: 9010
spring:
datasource:
url: jdbc:mysql://localhost:3306/test?characterEncoding=utf8
username: root
password: root
mybatis:
type-aliases-package: tk.mybatis.springboot.model
mapper-locations: classpath:mapper/*.xml
#mapper:
# mappers:
# - tk.mybatis.springboot.util.MyMapper
# not-empty: false
# identity: MYSQL
pagehelper:
helperDialect: mysql
reasonable: true
supportMethodsArguments: true
params: count=countSql
第三步:测试代码
@Test
public void testFindAllPage() {
// startPage(pageNum, pageSize);
PageHelper.startPage(1, 10);
//测试是验证发现如果参数超出了数据的范围,则pageHelper然后会返回数据,不会报错
//只是返回的数据为符合条件的最接近的值,比如总共 11条数据,如果用startPage(3, 10),则返回的是第11条数据(第2个分页的数据)。
//另外数据startPage(1, 10)和startPage(0, 10)都是查询的前10条数据
List<Person> persons = userMapper.findAllPage();
System.out.println("findAllPage:" + persons);
PageInfo<Person> pageInfo = new PageInfo<>(persons);
//pageInfo返回对象包含总的数据条数,当前页,每页显示数据,是否有前一页,后一页等各种实用信息
long totalCount = pageInfo.getTotal();
System.out.println("totalCount:" + (int)totalCount);
System.out.println("pageInfo:" + pageInfo);
//获取返回的数据
List<Person> lists = pageInfo.getList();
for (Person person : lists) {
System.out.println("person:" + person);
}
}
补充资料:
和 $ 的区别
mybatis做为一个轻量级ORM框架在许多项目中使用,因其简单的入门受到了广大开发者的热爱。在近期项目中再做一个相关的开发,碰到了#、$符号这样的问题,之前没怎么注意过,通过学习之后,有了点感悟,分享如下,
{}
使用#{}意味着使用的预编译的语句,即在使用jdbc时的preparedStatement,sql语句中如果存在参数则会使用?作占位符,我们知道这种方式可以防止sql注入,并且在使用#{}时形成的sql语句,已经带有引号,例,select * from table1 where id=#{id} 在调用这个语句时我们可以通过后台看到打印出的sql为:select * from table1 where id=’2’ 加入传的值为2.也就是说在组成sql语句的时候把参数默认为字符串。
${}
使用 时的sql不会当做字符串处理,是什么就是什么,如上边的语句:select∗fromtable1whereid= 时 的 s q l 不 会 当 做 字 符 串 处 理 , 是 什 么 就 是 什 么 , 如 上 边 的 语 句 : s e l e c t ∗ f r o m t a b l e 1 w h e r e i d = {id} 在调用这个语句时控制台打印的为:select * from table1 where id=2 ,假设传的参数值为2
从上边的介绍可以看出这两种方式的区别,我们最好是能用#{}则用它,因为它可以防止sql注入,且是预编译的,在需要原样输出时才使用${},如,
select * from tableNameorderby t a b l e N a m e o r d e r b y {id} 这里需要传入表名和按照哪个列进行排序 ,加入传入table1、id 则语句为:select * from table1 order by id
如果是使用#{} 则变成了select * from ‘table1’ order by ‘id’ 我们知道这样就不对了。
另,在使用以下的配置时,必须使用#{}
select * from message where id=#{id};
</select>
在parameterType是int时,sql语句中必须是#{}。
有不对之处欢迎之处!谢谢