我的编程空间,编程开发者的网络收藏夹
学习永远不晚

springboot整合持久层的方法实现

短信预约 -IT技能 免费直播动态提醒
省份

北京

  • 北京
  • 上海
  • 天津
  • 重庆
  • 河北
  • 山东
  • 辽宁
  • 黑龙江
  • 吉林
  • 甘肃
  • 青海
  • 河南
  • 江苏
  • 湖北
  • 湖南
  • 江西
  • 浙江
  • 广东
  • 云南
  • 福建
  • 海南
  • 山西
  • 四川
  • 陕西
  • 贵州
  • 安徽
  • 广西
  • 内蒙
  • 西藏
  • 新疆
  • 宁夏
  • 兵团
手机号立即预约

请填写图片验证码后获取短信验证码

看不清楚,换张图片

免费获取短信验证码

springboot整合持久层的方法实现

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</include>
                </includes>
            </resource>
            <resource>
                <directory>class="lazy" data-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;


@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;


@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整合持久层内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!

免责声明:

① 本站未注明“稿件来源”的信息均来自网络整理。其文字、图片和音视频稿件的所属权归原作者所有。本站收集整理出于非商业性的教育和科研之目的,并不意味着本站赞同其观点或证实其内容的真实性。仅作为临时的测试数据,供内部测试之用。本站并未授权任何人以任何方式主动获取本站任何信息。

② 本站未注明“稿件来源”的临时测试数据将在测试完成后最终做删除处理。有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341

springboot整合持久层的方法实现

下载Word文档到电脑,方便收藏和打印~

下载Word文档

猜你喜欢

SpringBoot整合mybatis/mybatis-plus实现数据持久化的操作

这篇文章主要介绍了SpringBoot整合mybatis/mybatis-plus实现数据持久化,本节内容我们介绍了数据持久化的相关操作,并且是基础传统的关系型数据库——mysql,需要的朋友可以参考下
2022-11-13

SpringBoot整合tkMapper的方法

项目使用SpringBoot2.0,H2数据库,使用了 Lombok 简化代码,下面是本人使用SpringBoot整合tkMapper的一个小demo,记录下来本人在此处踩得坑
2022-11-13

springboot整合RabbitMQ发送短信的实现方法

这篇文章主要介绍springboot整合RabbitMQ发送短信的实现方法,文中介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们一定要看完!RabbitMQ安装和运行# 安装rpm -ivh erlang-21.3.8.9-1.el7.
2023-06-15

SpringBoot整合第三方技术的实现

本文主要介绍了SpringBoot整合第三方技术的实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
2023-02-06

编程热搜

  • Python 学习之路 - Python
    一、安装Python34Windows在Python官网(https://www.python.org/downloads/)下载安装包并安装。Python的默认安装路径是:C:\Python34配置环境变量:【右键计算机】--》【属性】-
    Python 学习之路 - Python
  • chatgpt的中文全称是什么
    chatgpt的中文全称是生成型预训练变换模型。ChatGPT是什么ChatGPT是美国人工智能研究实验室OpenAI开发的一种全新聊天机器人模型,它能够通过学习和理解人类的语言来进行对话,还能根据聊天的上下文进行互动,并协助人类完成一系列
    chatgpt的中文全称是什么
  • C/C++中extern函数使用详解
  • C/C++可变参数的使用
    可变参数的使用方法远远不止以下几种,不过在C,C++中使用可变参数时要小心,在使用printf()等函数时传入的参数个数一定不能比前面的格式化字符串中的’%’符号个数少,否则会产生访问越界,运气不好的话还会导致程序崩溃
    C/C++可变参数的使用
  • css样式文件该放在哪里
  • php中数组下标必须是连续的吗
  • Python 3 教程
    Python 3 教程 Python 的 3.0 版本,常被称为 Python 3000,或简称 Py3k。相对于 Python 的早期版本,这是一个较大的升级。为了不带入过多的累赘,Python 3.0 在设计的时候没有考虑向下兼容。 Python
    Python 3 教程
  • Python pip包管理
    一、前言    在Python中, 安装第三方模块是通过 setuptools 这个工具完成的。 Python有两个封装了 setuptools的包管理工具: easy_install  和  pip , 目前官方推荐使用 pip。    
    Python pip包管理
  • ubuntu如何重新编译内核
  • 改善Java代码之慎用java动态编译

目录