SpringBoot数据访问Mybatis注解版,配置版,注解与配置一体版
注解版:
1.改druid 连接池,不改可以跳过这步
添加依赖
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.11</version>
</dependency>
修改配置文件:
application.yaml
spring:
datasource:
#driver-class-name: com.mysql.jdbc.Driver
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/activiti10unit?characterEncoding=utf-8&serverTimezone=GMT
username: root
password: root
#告知springboot 使用的链接池类型是druid
type: com.alibaba.druid.pool.DruidDataSource
initialSize: 20
maxActive: 30
minIdle: 10
userSSL: false
写mapper接口,加上@mapper注解
com.example.mybatis2018.mapper.UserMapper
package com.example.mybatis2018.mapper;
import com.example.mybatis2018.pojo.User;
import org.apache.ibatis.annotations.*;
import org.springframework.stereotype.Component;
/**
* 使用@Mapper主键 来标注这是一个Mapper接口
*/
@Mapper
public interface UserMapper {
@Select("select * from user where id = #{id}")
User selectUserbyId(Long id);
/**
* 自增主键 select last_insert_id()
* 非 自增主键 select uuid() before:true
* @param user
* @return
*/
//自增主键
@SelectKey(keyProperty = "id",keyColumn = "id",statement = "select last_insert_id()" ,before=false,resultType = Long.class)
@Insert("insert into user (USER_NAEM,USER_PASSWORD) values(#{USER_NAEM},#{USER_PASSWORD})")
int insertUser(User user);
@Delete("delete from user where id = #{id}")
int deleteUserById(Long id);
@Update("update user set USER_NAEM=#{USER_NAEM},USER_PASSWORD = #{USER_PASSWORD} where id = #{id}")
int updateUser(User user);
}
控制类访问得到数据
package com.example.mybatis2018.controller;
import com.example.mybatis2018.mapper.UserMapper;
import com.example.mybatis2018.mapper.UserMapperPeiZhi;
import com.example.mybatis2018.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class UderController {
@Autowired
private UserMapper userMapper;
@RequestMapping("/getUser/{id}")
@ResponseBody
public User getUserById(@PathVariable("id") Long id){
User u = new User();
u.setUSER_PASSWORD(DigestUtils.md5DigestAsHex("1111".getBytes()));
User user = userMapper.selectUserbyId(id);
System.out.println(user.toString());
return user;
}
}
配置版:
需要创建 映射文件与mybatis全局配置文件,并加载
配置文件的目录结构
SqlMapperConfig.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>
<!-- 配置分页插件 -->
<!-- <plugins>
<plugin interceptor="com.github.pagehelper.PageHelper">
<!– 设置数据库方言 –>
<property name="dialect" value="mysql"/>
</plugin>
</plugins>-->
<!-- 是用resource属性加载外部配置文件 -->
<!--<properties resource="db.properties">
<!– 如果外部配置文件有该属性,则内部定义属性被外部属性覆盖–>
<property name="jdbc.password" value="root123"/>
</properties>-->
<!-- 配置设置 -->
<!-- <settings>
<!– 如果要使用延迟加载,就必须配置这两个属性 –>
<setting name="lazyLoadingEnabled" value="true"/>
<setting name="aggressiveLazyLoading" value="false"/>
<!– 开启全局缓存 –>
<setting name="cacheEnabled" value="true"/>
</settings>-->
<!-- 类型别名 -->
<!-- 配置映射文件中使用的类型别名 -->
<!--<typeAliases>
<!– 给类型 com.igeek.crm.pojo.User取别名user–>
<typeAlias type="com.igeek.crm.pojo.User" alias="user"/>
<!– 配置一个包,让该包中所有的类都是用简称 –>
<package name="com.igeek.crm.pojo"/>
</typeAliases>-->
<!-- 和spring整合后 environments配置将废除 -->
<!-- <environments default="development">
<environment id="development">
<!– 使用jdbc事务管理 –>
<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>-->
<!-- 注册映射文件 -->
<!-- 将映射文件配置到mybatis的配置文件中 -->
<!--<mappers>-->
<!--
<mapper resource="sqlmap/UserMapper.xml"/>
-->
<!--
<mapper class="com.igeek.crm.mapper.UserMapper"/>
-->
<!--<package name="com.igeek.crm.mapper"/>
</mappers>-->
</configuration>
mybatis/mapper/userMapper.xml 映射文件
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.example.mybatis2018.mapper.UserMapperPeiZhi" >
<resultMap id="BaseResultMap" type="com.example.mybatis2018.pojo.User" >
<id column="ID" property="id" jdbcType="BIGINT" />
<result column="USER_NAEM" property="USER_NAEM" jdbcType="VARCHAR" />
<result column="USER_PASSWORD" property="USER_PASSWORD" jdbcType="VARCHAR" />
</resultMap>
<select id="selectUserbyId" resultMap="BaseResultMap" parameterType="long">
select * from user where id = #{id}
</select>
<select id="selectUserbyId3" resultMap="BaseResultMap" parameterType="long">
select * from user where id = #{id}
</select>
<insert id="insertUser" parameterType="com.example.mybatis2018.pojo.User">
<selectKey keyColumn="ID" keyProperty="id" order="AFTER" resultType="long">
SELECT last_insert_id()
</selectKey>
insert into user (USER_NAEM,USER_PASSWORD) values(#{USER_NAEM},#{USER_PASSWORD})
</insert>
</mapper>
加载配置文件:
application.yaml
spring:
datasource:
#driver-class-name: com.mysql.jdbc.Driver
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/activiti10unit?characterEncoding=utf-8&serverTimezone=GMT
username: root
password: root
#告知springboot 使用的链接池类型是druid
type: com.alibaba.druid.pool.DruidDataSource
initialSize: 20
maxActive: 30
minIdle: 10
userSSL: false
mybatis:
config-location: classpath:/mybatis/SqlMapperConfig.xml #加载mybatis全局配置文件
mapper-locations: classpath:/mybatis/mapper/userMapper.xml #加载配置映射文件路径
在启动类中扫描mapper接口:
com.example.mybatis2018.Mybatis2018Application
提示:启动类扫描Mapper接口与mapper接口类上的 @mapper 注解扫描,两个扫描方式任意选一个做接口扫描就可以了
package com.example.mybatis2018;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@MapperScan("com.example.mybatis2018.mapper")
//@ImportResource(locations="classpath: interceptor.xml")//扫描拦截器xml文件
@SpringBootApplication
public class Mybatis2018Application {
public static void main(String[] args) {
SpringApplication.run(Mybatis2018Application.class, args);
}
}
创建mapper接口:
com.example.mybatis2018.mapper.UserMapperPeiZhi
package com.example.mybatis2018.mapper;
import org.apache.ibatis.annotations.*;
import com.example.mybatis2018.pojo.User;
public interface UserMapperPeiZhi {
User selectUserbyId(Long id);
int insertUser(User user);
int deleteUserById(Long id);
int updateUser(User user);
}
控制类访问得到数据
package com.example.mybatis2018.controller;
import com.example.mybatis2018.mapper.UserMapper;
import com.example.mybatis2018.mapper.UserMapperPeiZhi;
import com.example.mybatis2018.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class UderController {
@Autowired
private UserMapperPeiZhi userMapperPeiZhi;//配置版mapper接口
@RequestMapping("/getUser2/{id}")
@ResponseBody
public User getUserById2(@PathVariable("id") Long id){
User u = new User();
u.setUSER_PASSWORD(DigestUtils.md5DigestAsHex("1111".getBytes()));
User user = userMapperPeiZhi.selectUserbyId(id);
System.out.println(user.toString());
return user;
}
}
注解与配置一体版
就是在原有的配置版的mapper接口上加@mapper注解,后在接口方法上加注解写SQL,
但是要注意的是,映射文件中对应的接口方法上不允许写注解SQL,也就是接口中的方法只能采用一种方式获取数据,
要么注解方式获取要么从映射文件中获取;
mapper接口
提示:启动类扫描Mapper接口与mapper接口类上的 @mapper 注解扫描,两个扫描方式任意选一个做接口扫描就可以了
package com.example.mybatis2018.mapper;
import org.apache.ibatis.annotations.*;
import com.example.mybatis2018.pojo.User;
/**
* 使用@Mapper主键 来标注这是一个Mapper接口
*/
@Mapper
public interface UserMapperPeiZhi {
@Select("select * from user where id = #{id}")
User selectUserbyId2(Long id);
User selectUserbyId(Long id);
int insertUser(User user);
int deleteUserById(Long id);
int updateUser(User user);
}
控制类访问得到数据
package com.example.mybatis2018.controller;
import com.example.mybatis2018.mapper.UserMapper;
import com.example.mybatis2018.mapper.UserMapperPeiZhi;
import com.example.mybatis2018.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class UderController {
@Autowired
private UserMapper userMapper;//注解版
@Autowired
private UserMapperPeiZhi userMapperPeiZhi;//注解与配置混合版
@RequestMapping("/getUser/{id}")
@ResponseBody
public User getUserById(@PathVariable("id") Long id){
//注解版
User user = userMapper.selectUserbyId(id);
System.out.println(user.toString());
return user;
}
@RequestMapping("/getUser2/{id}")
@ResponseBody
public User getUserById2(@PathVariable("id") Long id){
//注解与配置混合版,调配置获取数据
User user = userMapperPeiZhi.selectUserbyId(id);
System.out.println(user.toString());
return user;
}
@RequestMapping("/getUser3/{id}")
@ResponseBody
public User getUserById3(@PathVariable("id") Long id){
//注解与配置混合版,调注解获取数据
User user = userMapperPeiZhi.selectUserbyId2(id);
System.out.println(user.toString());
return user;
}
}
pom
<?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.example</groupId>
<artifactId>mybatis2018</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>mybatis2018</name>
<description>Demo project for Spring Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.0.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.2</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.11</version>
</dependency>
<!--能够在写配置文件的时候有提示-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
<!--引用thymeleaf启动器-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<!--https://www.webjars.org/-->
<!-- <dependency>
<groupId>org.webjars</groupId>
<artifactId>jquery</artifactId>
<version>3.3.1-1</version>
</dependency>
<dependency>
<groupId>org.webjars</groupId>
<artifactId>bootstrap</artifactId>
<version>4.1.3</version>
</dependency>
<dependency>
<groupId>org.webjars</groupId>
<artifactId>jquery-ui</artifactId>
<version>1.12.1</version>
</dependency>
<dependency>
<groupId>org.webjars.npm</groupId>
<artifactId>jquery-easyui</artifactId>
<version>1.5.21</version>
</dependency>-->
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
pojo:
package com.example.mybatis2018.pojo;
//@Component
//@ConfigurationProperties(prefix = "user")
public class User {
private Long id ;
private String USER_NAEM;
private String USER_PASSWORD;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getUSER_NAEM() {
return USER_NAEM;
}
public void setUSER_NAEM(String USER_NAEM) {
this.USER_NAEM = USER_NAEM;
}
public String getUSER_PASSWORD() {
return USER_PASSWORD;
}
public void setUSER_PASSWORD(String USER_PASSWORD) {
this.USER_PASSWORD = USER_PASSWORD;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", USER_NAEM='" + USER_NAEM + '\'' +
", USER_PASSWORD='" + USER_PASSWORD + '\'' +
'}';
}
}