springboot整合持久层的方法实现

目录
  • 1. springboot整合jdbcTemplate
    • 1.1 pom.xml
    • 1.2 application.properties
    • 1.3 model
    • 1.4 service
    • 1.5 serviceImpl,crud案例
  • 2. jdbcTemplate配置多数据源
    • 2.1 pom.xml
    • 2.2 application.properties
    • 2.3 实体类
    • 2.4 数据源配置
    • 2.5 jdbctemplate配置
    • 2.6 注入模板测试
  • 3. springboot整合mybatis(注解方式)
    • 3.1 pom.xml
    • 3.2 application.properties
    • 3.3 实体类
    • 3.4 mapper
    • 3.5 service
    • 3.6 srviceImpl
    • 3.7 扫描mapper
    • 3.8 测试
  • 4. springboot整合mybatis(xml方式)
    • 4.1 pom.xml
    • 4.2 application.xml
    • 4.3 实体类
    • 4.4 mapper
    • 4.5 mapper.xml
    • 4.6 service
    • 4.7 serviceImpl
    • 4.8 扫描mapper
  • 5. mybatis整合多数据源
    • 5.1 pom.xml
    • 5.2 application.properties
    • 5.3 实体类
    • 5.4 mapper1
    • 5.5 mapper2
    • 5.6 mapper1.xml
    • 5.7 mapper2.xml
    • 5.8 数据源配置
    • 5.9 mybatis配置1
    • 5.10 mybatis配置2
    • 5.11 项目结构

1. springboot整合jdbcTemplate

1.1 pom.xml

<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.5.5</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.yl</groupId>
    <artifactId>jdbctemplate</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>jdbctemplate</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </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>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

1.2 application.properties

spring.datasource.url=jdbc:mysql://localhost:3306/demo?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf-8
spring.datasource.username=root
spring.datasource.password=root

1.3 model

package com.yl.jdbctemplate.model;

import java.io.Serializable;

public class Student implements Serializable {
    private Integer id;
    private String stuName;
    private String stuNo;
    private Integer age;
    private String stuMessage;

    @Override
    public String toString() {
        return "Student{" +
                "id=" + id +
                ", stuName='" + stuName + '\'' +
                ", stuNo='" + stuNo + '\'' +
                ", age=" + age +
                ", stuMessage='" + stuMessage + '\'' +
                '}';
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getStuName() {
        return stuName;
    }

    public void setStuName(String stuName) {
        this.stuName = stuName;
    }

    public String getStuNo() {
        return stuNo;
    }

    public void setStuNo(String stuNo) {
        this.stuNo = stuNo;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public String getStuMessage() {
        return stuMessage;
    }

    public void setStuMessage(String stuMessage) {
        this.stuMessage = stuMessage;
    }
}

1.4 service

package com.yl.jdbctemplate.service;

import com.yl.jdbctemplate.model.Student;

import java.util.List;

public interface StudentService {

    int addStudent(Student student);

    int addStudent2(Student student);

    int updateStudent(Student student);

    int deleteStudentById(Integer id);

    List<Student> getAllStudent();

    List<Student> getAllStudent2();
}

1.5 serviceImpl,crud案例

package com.yl.jdbctemplate.service.impl;

import com.yl.jdbctemplate.model.Student;
import com.yl.jdbctemplate.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementCreator;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.stereotype.Service;

import java.sql.*;
import java.util.List;

@Service
public class StudentServiceImpl implements StudentService {
    @Autowired
    JdbcTemplate jdbcTemplate;

    @Override
    public int addStudent(Student student) {
        int result = jdbcTemplate.update("insert into student(stu_name,stu_no,age,stu_message) values(?,?,?,?) "
                ,student.getStuName(),student.getStuNo(),student.getAge(),student.getStuMessage());
        return result;
    }

    //插入数据,并且回写id
    @Override
    public int addStudent2(Student student) {
        GeneratedKeyHolder keyHolder = new GeneratedKeyHolder();
        int result = jdbcTemplate.update(new PreparedStatementCreator() {
            @Override
            public PreparedStatement createPreparedStatement(Connection con) throws SQLException {
                //插入数据后返回主键
                PreparedStatement ps = con.prepareStatement("insert into student(stu_name,stu_no,age,stu_message) values(?,?,?,?)"
                        , Statement.RETURN_GENERATED_KEYS);
                ps.setString(1,student.getStuName());
                ps.setString(2,student.getStuNo());
                ps.setInt(3,student.getAge());
                ps.setString(4,student.getStuMessage());
                return ps;
            }
        },keyHolder);
        student.setId(keyHolder.getKey().intValue());
        return result;
    }

    @Override
    public int updateStudent(Student student) {
        int result = jdbcTemplate.update("update student set stu_name=?,stu_no=?,age=?,stu_message=? where id = ?",
                student.getStuName(),student.getStuNo(),student.getAge(),student.getStuMessage(),student.getId());
        return result;
    }

    @Override
    public int deleteStudentById(Integer id) {
        int result = jdbcTemplate.update("delete from student where id = ?", id);
        return result;
    }

    //这种查询比较麻烦,要一个一个设值
    @Override
    public List<Student> getAllStudent() {
        List<Student> list = jdbcTemplate.query("select * from student", new RowMapper<Student>() {
            @Override
            public Student mapRow(ResultSet rs, int rowNum) throws SQLException {
                int id = rs.getInt("id");
                String stuName = rs.getString("stu_name");
                String stuNo = rs.getString("stu_no");
                int age = rs.getInt("age");
                String stuMessage = rs.getString("stu_message");
                Student student = new Student();
                student.setId(id);
                student.setStuName(stuName);
                student.setStuNo(stuNo);
                student.setAge(age);
                student.setStuMessage(stuMessage);
                return student;
            }
        });
        return list;
    }

    //这种方式比较方便,但是有一个前提:数据库表的字段和java实体类的属性名要完全一致
    //或者数据库表的字段下划线命名方式对应java实体类属性名的驼峰命名方式
    @Override
    public List<Student> getAllStudent2() {
        List<Student> list = jdbcTemplate.query("select * from student",new BeanPropertyRowMapper<>(Student.class));
        return list;
    }
}

2. jdbcTemplate配置多数据源

2.1 pom.xml

<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.5.5</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.yl</groupId>
    <artifactId>jdbctemplateutil</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>jdbctemplateutil</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </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>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

2.2 application.properties

# springboot配置多数据源

spring.datasource.one.username=root
spring.datasource.one.password=root
spring.datasource.one.jdbcurl=jdbc:mysql://localhost:3306/demo?useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai

spring.datasource.two.username=root
spring.datasource.two.password=root
spring.datasource.two.jdbcurl=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai

2.3 实体类

package com.yl.jdbctemplateutil.model;

import java.io.Serializable;

public class Student implements Serializable {
    private Integer id;
    private String stuName;
    private String stuNo;
    private Integer age;
    private String stuMessage;

    @Override
    public String toString() {
        return "Student{" +
                "id=" + id +
                ", stuName='" + stuName + '\'' +
                ", stuNo='" + stuNo + '\'' +
                ", age=" + age +
                ", stuMessage='" + stuMessage + '\'' +
                '}';
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getStuName() {
        return stuName;
    }

    public void setStuName(String stuName) {
        this.stuName = stuName;
    }

    public String getStuNo() {
        return stuNo;
    }

    public void setStuNo(String stuNo) {
        this.stuNo = stuNo;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public String getStuMessage() {
        return stuMessage;
    }

    public void setStuMessage(String stuMessage) {
        this.stuMessage = stuMessage;
    }
}

2.4 数据源配置

package com.yl.jdbctemplateutil.config;

import com.zaxxer.hikari.HikariDataSource;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;

@Configuration
public class DatasourceConfig {

    @Bean
    @ConfigurationProperties(prefix = "spring.datasource.one")
    DataSource dsOne() {
        return new HikariDataSource();
    }

    @Bean
    @ConfigurationProperties(prefix = "spring.datasource.two")
    DataSource dsTwo() {
        return new HikariDataSource();
    }
}

2.5 jdbctemplate配置

package com.yl.jdbctemplateutil.config;

import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.JdbcTemplate;

import javax.sql.DataSource;

@Configuration
public class JdbcTemplateConfig {
    @Bean
    JdbcTemplate jdbcTemplateOne(@Qualifier("dsOne")DataSource dataSource) {
        return new JdbcTemplate(dataSource);
    }

    @Bean
    JdbcTemplate jdbcTemplateTwo(@Qualifier("dsTwo")DataSource dataSource) {
        return new JdbcTemplate(dataSource);
    }
}

2.6 注入模板测试

3. springboot整合mybatis(注解方式)

3.1 pom.xml

<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.5.5</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.yl</groupId>
    <artifactId>mybatis</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>mybatis</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <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>2.2.0</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>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

3.2 application.properties

# 数据源配置
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.url=jdbc:mysql://localhost:3306/demo?useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai

3.3 实体类

package com.yl.mybatis.model;

import java.io.Serializable;

public class Student implements Serializable {
    private Integer id;
    private String stuName;
    private String stuNo;
    private Integer age;
    private String stuMessage;

    @Override
    public String toString() {
        return "Student{" +
                "id=" + id +
                ", stuName='" + stuName + '\'' +
                ", stuNo='" + stuNo + '\'' +
                ", age=" + age +
                ", stuMessage='" + stuMessage + '\'' +
                '}';
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getStuName() {
        return stuName;
    }

    public void setStuName(String stuName) {
        this.stuName = stuName;
    }

    public String getStuNo() {
        return stuNo;
    }

    public void setStuNo(String stuNo) {
        this.stuNo = stuNo;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public String getStuMessage() {
        return stuMessage;
    }

    public void setStuMessage(String stuMessage) {
        this.stuMessage = stuMessage;
    }
}

3.4 mapper

package com.yl.mybatis.mapper;

import com.yl.mybatis.model.Student;
import org.apache.ibatis.annotations.*;

import java.util.List;

public interface StudentMapper {
    @Select("select * from student where id = #{id}")
    Student getStudentById(Integer id);

    @Insert("insert into student(stu_name,stu_no,age,stu_message) values(#{stuName},#{stuNo},#{age},#{stuMessage})")
    //回写id
    @SelectKey(statement = "select last_insert_id()",keyProperty = "id",before = false,resultType = Integer.class)
    Integer addStudent(Student student);

    //表字段和java实体属性映射
    @Results({
            @Result(property = "stuName",column = "stu_name"),
            @Result(property = "stuNo",column = "stu_no"),
            @Result(property = "stuMessage",column = "stu_message")
    })
    @Select("select * from student")
    List<Student> getAllStudent();

    @Delete("delete from student where id = #{id}")
    Integer deleteById(Integer id);

    @Update("update student set stu_name = #{stuName},stu_no = #{stuNo},age = #{age},stu_message = #{stuMessage} where id = #{id}")
    Integer updateByStudent(Student student);
}

3.5 service

package com.yl.mybatis.service;

import com.yl.mybatis.model.Student;

import java.util.List;

public interface StudentService {
    Student getStudentById(Integer id);

    Integer addStudent(Student student);

    List<Student> getAllStudent();

    Integer deleteById(Integer id);

    Integer updateById(Student student);
}

3.6 srviceImpl

package com.yl.mybatis.service.impl;

import com.yl.mybatis.mapper.StudentMapper;
import com.yl.mybatis.model.Student;
import com.yl.mybatis.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class StudentServiceImpl implements StudentService {
    @Autowired
    private StudentMapper studentMapper;

    @Override
    public Student getStudentById(Integer id) {
        return studentMapper.getStudentById(id);
    }

    @Override
    public Integer addStudent(Student student) {
        return studentMapper.addStudent(student);
    }

    @Override
    public List<Student> getAllStudent() {
        return studentMapper.getAllStudent();
    }

    @Override
    public Integer deleteById(Integer id) {
        return studentMapper.deleteById(id);
    }

    @Override
    public Integer updateById(Student student) {
        return studentMapper.updateByStudent(student);
    }
}

3.7 扫描mapper

3.8 测试

4. springboot整合mybatis(xml方式)

4.1 pom.xml

<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.5.5</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.yl</groupId>
    <artifactId>mybatis</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>mybatis</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <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>2.2.0</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>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

4.2 application.xml

# 数据源配置
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.url=jdbc:mysql://localhost:3306/demo?useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai

# mybatis配置
# 扫描xml文件
mybatis.mapper-locations=classpath:mapper/*.xml

4.3 实体类

package com.yl.mybatis.model;

import java.io.Serializable;

public class Student implements Serializable {
    private Integer id;
    private String stuName;
    private String stuNo;
    private Integer age;
    private String stuMessage;

    @Override
    public String toString() {
        return "Student{" +
                "id=" + id +
                ", stuName='" + stuName + '\'' +
                ", stuNo='" + stuNo + '\'' +
                ", age=" + age +
                ", stuMessage='" + stuMessage + '\'' +
                '}';
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getStuName() {
        return stuName;
    }

    public void setStuName(String stuName) {
        this.stuName = stuName;
    }

    public String getStuNo() {
        return stuNo;
    }

    public void setStuNo(String stuNo) {
        this.stuNo = stuNo;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public String getStuMessage() {
        return stuMessage;
    }

    public void setStuMessage(String stuMessage) {
        this.stuMessage = stuMessage;
    }
}

4.4 mapper

package com.yl.mybatis.mapper;

import com.yl.mybatis.model.Student;
import java.util.List;

public interface StudentMapper {

    Student getStudentById(Integer id);

    Integer addStudent(Student student);

    List<Student> getAllStudent();

    Integer deleteById(Integer id);

    Integer updateById(Student student);
}

4.5 mapper.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.yl.mybatis.mapper.StudentMapper">

    <resultMap id="BaseResultMap" type="com.yl.mybatis.model.Student">
        <id property="id" column="id"/>
        <result property="stuName" column="stu_name"/>
        <result property="stuNo" column="stu_no"/>
        <result property="age" column="age"/>
        <result property="stuMessage" column="stu_message"/>
    </resultMap>

    <select id="getStudentById" resultMap="BaseResultMap">
        select * from student where id = #{id}
    </select>

    <select id="getAllStudent" resultMap="BaseResultMap">
        select * from student
    </select>

    <!--回写id-->
    <insert id="addStudent" useGeneratedKeys="true" keyProperty="id">
        insert into student(stu_name,stu_no,age,stu_message) values(#{stuName},#{stuNo},#{age},#{stuMessage})
    </insert>

    <delete id="deleteById" parameterType="java.lang.Integer">
        delete from student where id = #{id}
    </delete>

    <update id="updateById" parameterType="com.yl.mybatis.model.Student">
        update student set stu_name=#{stuName},stu_no=#{stuNo},age=#{age},stu_message=#{stuMessage} where id = #{id}
    </update>
</mapper>

4.6 service

package com.yl.mybatis.service;

import com.yl.mybatis.model.Student;

import java.util.List;

public interface StudentService {
    Student getStudentById(Integer id);

    Integer addStudent(Student student);

    List<Student> getAllStudent();

    Integer deleteById(Integer id);

    Integer updateById(Student student);
}

4.7 serviceImpl

package com.yl.mybatis.service.impl;

import com.yl.mybatis.mapper.StudentMapper;
import com.yl.mybatis.model.Student;
import com.yl.mybatis.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class StudentServiceImpl implements StudentService {
    @Autowired
    private StudentMapper studentMapper;

    @Override
    public Student getStudentById(Integer id) {
        return studentMapper.getStudentById(id);
    }

    @Override
    public Integer addStudent(Student student) {
        return studentMapper.addStudent(student);
    }

    @Override
    public List<Student> getAllStudent() {
        return studentMapper.getAllStudent();
    }

    @Override
    public Integer deleteById(Integer id) {
        return studentMapper.deleteById(id);
    }

    @Override
    public Integer updateById(Student student) {
        return studentMapper.updateById(student);
    }
}

4.8 扫描mapper

5. mybatis整合多数据源

5.1 pom.xml

<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.5.5</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.yl</groupId>
    <artifactId>mybatisutil</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>mybatisutil</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <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>2.2.0</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>
    </dependencies>

    <build>
        <resources>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.xml</include>
                </includes>
            </resource>
            <resource>
                <directory>src/main/resources</directory>
            </resource>
        </resources>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

5.2 application.properties

# 数据源配置
spring.datasource.one.username=root
spring.datasource.one.password=root
spring.datasource.one.jdbcurl=jdbc:mysql://localhost:3306/demo?useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai

spring.datasource.two.username=root
spring.datasource.two.password=root
spring.datasource.two.jdbcurl=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai

5.3 实体类

package com.yl.mybatisutil.model;

import java.io.Serializable;

public class Student implements Serializable {
    private Integer id;
    private String stuName;
    private String stuNo;
    private Integer age;
    private String stuMessage;

    @Override
    public String toString() {
        return "Student{" +
                "id=" + id +
                ", stuName='" + stuName + '\'' +
                ", stuNo='" + stuNo + '\'' +
                ", age=" + age +
                ", stuMessage='" + stuMessage + '\'' +
                '}';
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getStuName() {
        return stuName;
    }

    public void setStuName(String stuName) {
        this.stuName = stuName;
    }

    public String getStuNo() {
        return stuNo;
    }

    public void setStuNo(String stuNo) {
        this.stuNo = stuNo;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public String getStuMessage() {
        return stuMessage;
    }

    public void setStuMessage(String stuMessage) {
        this.stuMessage = stuMessage;
    }
}

5.4 mapper1

package com.yl.mybatisutil.mapper1;

import com.yl.mybatisutil.model.Student;

import java.util.List;

public interface StudentMapper1 {
    List<Student> getAllStudent();
}

5.5 mapper2

package com.yl.mybatisutil.mapper2;

import com.yl.mybatisutil.model.Student;

import java.util.List;

public interface StudentMapper2 {
    List<Student> getAllStudent();
}

5.6 mapper1.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.yl.mybatisutil.mapper1.StudentMapper1">
    <select id="getAllStudent" resultType="com.yl.mybatisutil.model.Student">
        select * from student
    </select>
</mapper>

5.7 mapper2.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.yl.mybatisutil.mapper2.StudentMapper2">
    <select id="getAllStudent" resultType="com.yl.mybatisutil.model.Student">
        select * from student
    </select>
</mapper>

5.8 数据源配置

package com.yl.mybatisutil.config;

import com.zaxxer.hikari.HikariDataSource;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;

/**
 * 多数据源配置
 */
@Configuration
public class DataSourceConfig {

    @Bean
    @ConfigurationProperties(prefix = "spring.datasource.one")
    DataSource dsOne() {
        return new HikariDataSource();
    }
    @Bean
    @ConfigurationProperties(prefix = "spring.datasource.two")
    DataSource dsTwo() {
        return new HikariDataSource();
    }
}

5.9 mybatis配置1

package com.yl.mybatisutil.config;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;

/**
 *  mybatis的配置
 */
@Configuration
@MapperScan(basePackages = "com.yl.mybatisutil.mapper1",sqlSessionFactoryRef = "sqlSessionFactory1",sqlSessionTemplateRef = "sqlSessionTemplate1")
public class MyBatisConfigOne {
    @Qualifier("dsOne")
    @Autowired
    DataSource dataSource;

    @Bean
    SqlSessionFactory sqlSessionFactory1() {
        try {
            SqlSessionFactory sqlSessionFactory = null;
            SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
            sqlSessionFactoryBean.setDataSource(dataSource);
            sqlSessionFactory = sqlSessionFactoryBean.getObject();
            return sqlSessionFactory;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    @Bean
    SqlSessionTemplate sqlSessionTemplate1() {
        return new SqlSessionTemplate(sqlSessionFactory1());
    }

}

5.10 mybatis配置2

package com.yl.mybatisutil.config;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;

/**
 *  mybatis的配置
 */
@Configuration
@MapperScan(basePackages = "com.yl.mybatisutil.mapper2",sqlSessionFactoryRef = "sqlSessionFactory2",sqlSessionTemplateRef = "sqlSessionTemplate2")
public class MyBatisConfigTwo {
    @Qualifier("dsTwo")
    @Autowired
    DataSource dataSource;

    @Bean
    SqlSessionFactory sqlSessionFactory2() {
        try {
            SqlSessionFactory sqlSessionFactory = null;
            SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
            sqlSessionFactoryBean.setDataSource(dataSource);
            sqlSessionFactory = sqlSessionFactoryBean.getObject();
            return sqlSessionFactory;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    @Bean
    SqlSessionTemplate sqlSessionTemplate2() {
        return new SqlSessionTemplate(sqlSessionFactory2());
    }

}

5.11 项目结构

到此这篇关于springboot整合持久层的方法实现的文章就介绍到这了,更多相关springboot整合持久层内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!

(0)

相关推荐

  • SpringBoot集成JPA持久层框架,简化数据库操作

    目录 与SpringBoot2.0整合 1.核心依赖 2.配置文件 3.实体类对象 4.JPA框架的用法 5.封装一个服务层逻辑 测试代码块 源代码地址 与SpringBoot2.0整合 1.核心依赖 <!-- JPA框架 --> <dependency>     <groupId>org.springframework.boot</groupId>     <artifactId>spring-boot-starter-data-jpa<

  • springboot整合持久层的方法实现

    目录 1. springboot整合jdbcTemplate 1.1 pom.xml 1.2 application.properties 1.3 model 1.4 service 1.5 serviceImpl,crud案例 2. jdbcTemplate配置多数据源 2.1 pom.xml 2.2 application.properties 2.3 实体类 2.4 数据源配置 2.5 jdbctemplate配置 2.6 注入模板测试 3. springboot整合mybatis(注解方

  • SpringBoot 整合Redis 数据库的方法

    Redis简介 Redis(官网: https://redis.io )是一个基于内存的日志型可持久化的缓存数据库,保存形式为key-value格式,Redis完全免费开源,它使用ANSI C语言编写.与其他的key - value缓存产品一样,Redis具有以下三个特点. • Redis支持数据的持久化,可以将内存中的数据保存在磁盘中,重启的时候可以再次加载进行使用: • Redis不仅支持简单的key-value类型数据,同时还提供字符串.链表.集合.有序集合和哈希等数据结构的存储: • R

  • Spring Boot 整合持久层之JdbcTemplate

    目录 整合JdbcTemplate 创建数据库和表 创建项目 数据库配置 创建实体类 创建数据库访问层 创建 Service 和 Controller 整合JdbcTemplate JdbcTemplate 是 Spring 提供的一套 JDBC 模板框架,利用 AOP 技术来解决直接使用 JDBC 时大量重复代码的问题.JdbcTemplate 虽然没有 Mybatis 灵活,但是比直接使用 JDBC 方便很多.Spring Boot 中对 JdbcTemplate 的使用提供了自动化配置类

  • Spring Boot整合持久层之JPA多数据源

    目录 JPA 多数据源 准备工作 创建 JPA 配置 创建 Repository 创建 Controller JPA 多数据源 JPA 和 MyBatis 配置多数据源类似,不同的是,JPA 配置时主要提供不同的 LocalContainerEntityManagerFactoryBean 以及事务管理器. 项目目录结构如下: 准备工作 创建 Spring Boot Web 项目,添加如下依赖: <dependency> <groupId>org.springframework.b

  • Spring Boot整合持久层之JdbcTemplate多数据源

    目录 多数据源 JdbcTemplate 多数据源 1. 创建数据库 2.创建项目 3. 配置数据库连接 4. 配置数据源 5. 配置 JdbcTemplate 6. 创建BookController 7. 测试 多数据源 所谓多数据源,就是一个 Java EE 项目中采用了不同数据库实例中的多个库,或者同一个数据库实例中多个不同的库.一般来说,采用 MyCat 等分布式数据库中间件是比较好的解决方案,这样可以把数据库读写分离.分库分表.备份等操作交给中间件去做,Java 代码只需要专注于业务即

  • Spring Boot 整合持久层之Spring Data JPA

    目录 整合Spring Data JPA 1. 创建数据库 2. 创建项目 3. 数据库配置 4. 创建实体类 5. 创建 BookDao 接口 6. 创建 BookService 7. 创建 BookController 8. 测试 整合Spring Data JPA JPA (Java Persistence API)和 Spring Data 是两个范畴的概念. Hibernate 是一个 ORM 框架,JPA 则是一种ORM,JPA 和 Hibernate 的关系就像 JDBC 与 JD

  • Spring Boot 整合持久层之MyBatis

    目录 整合MyBatis 1. 创建项目 2. 创表实体类等 3. 创建数据库访问层 4. 创建 BookMapper.xml 5. 创建Service和BookController 6. 配置 pom.xml 文件 整合MyBatis MyBatis 是一款优秀的持久层框架,原名 iBatis ,2010年迁移到 Goole Code 并改名为 MyBatis ,2013年迁移到 GitHub 上.MyBatis 支持定制化 SQL .存储过程及高级映射.MyBatis 几乎避免了所有的 JD

  • PHP基于MySQL数据库实现对象持久层的方法

    本文实例讲述了PHP基于MySQL数据库实现对象持久层的方法.分享给大家供大家参考.具体如下: 心血来潮,做了一下PHP的对象到数据库的简单持久层. 不常用PHP,对PHP也不熟,关于PHP反射的大部分内容都是现学的. 目前功能比较弱,只是完成一些简单的工作,对象之间的关系还没法映射,并且对象的成员只能支持string或者integer两种类型的. 成员变量的值也没有转义一下... 下面就贴一下代码: 首先是数据库的相关定义,该文件定义了数据库的连接属性: <?php /* * Filename

  • SpringBoot整合Druid数据源的方法实现

    目录 1.在创建SpringBoot项目的时候,在pom.xml maven中添加依赖: 2.在 application.yml(或aproperties)中添加相应的配置: 3. log4j.properties 配置文件: 4.在运行测试方法,查看数据源 5.运行测试方法 SprintBoot 默认使用的是 HikariDataSource数据源,这次整合一个第三方的数据源 Druid ,它是阿里开发的一款开源的数据源,被很多人认为是Java语言中最好的数据库连接池,因为 Druid 能够提

  • SpringBoot整合Mybatis与MybatisPlus方法详细讲解

    目录 一.整合MyBatis操作 1.配置模式 2.注解模式 3.混合模式 二.整合 MyBatis-Plus 完成CRUD 1.什么是MyBatis-Plus 2.整合MyBatis-Plus 3.CRUD功能 一.整合MyBatis操作 官网:MyBatis · GitHub SpringBoot官方的Starter:spring-boot-starter-* 第三方的starter的格式: *-spring-boot-starter <dependency> <groupId>

随机推荐