1. 程式人生 > >SpringBoot資料訪問Mybatis註解版,配置版,註解與配置一體版

SpringBoot資料訪問Mybatis註解版,配置版,註解與配置一體版

                                            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">
			&lt;!&ndash; 設定資料庫方言 &ndash;&gt;
			<property name="dialect" value="mysql"/>
		</plugin>
	</plugins>-->

	<!-- 是用resource屬性載入外部配置檔案 -->
	<!--<properties resource="db.properties">
		&lt;!&ndash; 如果外部配置檔案有該屬性,則內部定義屬性被外部屬性覆蓋&ndash;&gt;
		<property name="jdbc.password" value="root123"/>
	</properties>-->
	<!-- 配置設定 -->
<!--	<settings>
		&lt;!&ndash; 如果要使用延遲載入,就必須配置這兩個屬性 &ndash;&gt;
		<setting name="lazyLoadingEnabled" value="true"/>
		<setting name="aggressiveLazyLoading" value="false"/>
		&lt;!&ndash; 開啟全域性快取 &ndash;&gt;
		<setting name="cacheEnabled" value="true"/>
	</settings>-->
	<!-- 類型別名 -->
	<!-- 配置對映檔案中使用的類型別名 -->
	<!--<typeAliases>
		&lt;!&ndash; 給型別 com.igeek.crm.pojo.User取別名user&ndash;&gt;
		<typeAlias type="com.igeek.crm.pojo.User" alias="user"/>
		&lt;!&ndash; 配置一個包,讓該包中所有的類都是用簡稱 &ndash;&gt;
		<package name="com.igeek.crm.pojo"/>
	</typeAliases>-->



	<!-- 和spring整合後 environments配置將廢除 -->
<!--	<environments default="development">
		<environment id="development">
			&lt;!&ndash; 使用jdbc事務管理 &ndash;&gt;
			<transactionManager type="JDBC" />
			&lt;!&ndash; 資料庫連線池 &ndash;&gt;
			<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 + '\'' +
                '}';
    }
}