MyBatis-Spring 整合 Spring Core

发布于 2024-11-06 00:04:26 字数 8537 浏览 6 评论 0

目录结构:

D:.
│   pom.xml
│
└───src
  ├───main
  │   ├───java
  │   │   └───net
  │   │     └───wuxianjie
  │   │       └───demo
  │   │         │   Main.java
  │   │         │
  │   │         ├───config
  │   │         │     DatabaseConfig.java
  │   │         │
  │   │         ├───domain
  │   │         │     User.java
  │   │         │
  │   │         ├───mapper
  │   │         │     UserMapper.java
  │   │         │
  │   │         └───service
  │   │             UserService.java
  │   │
  │   └───resources
  │     │   hikari.properties
  │     │   mybatis-config.xml
  │     │
  │     └───mappers
  │         UserMapper.xml
  │
  └───test
    └───java

依赖

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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>net.wuxianjie</groupId>
  <artifactId>demo-mybatis-spring</artifactId>
  <version>1.0-SNAPSHOT</version>

  <properties>
  <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  <maven.compiler.source>1.8</maven.compiler.source>
  <maven.compiler.target>1.8</maven.compiler.target>
  </properties>

  <dependencies>
  <!-- MyBatis-Spring -->
  <dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis-spring</artifactId>
    <version>2.0.5</version>
  </dependency>

  <dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis</artifactId>
    <version>3.5.5</version>
  </dependency>

  <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context</artifactId>
    <version>5.2.6.RELEASE</version>
  </dependency>

  <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-jdbc</artifactId>
    <version>5.2.6.RELEASE</version>
  </dependency>

  <dependency>
    <groupId>org.springframework.batch</groupId>
    <artifactId>spring-batch-infrastructure</artifactId>
    <version>4.2.2.RELEASE</version>
  </dependency>
  <!-- ./MyBatis-Spring -->

  <!-- 数据库相关 -->
  <dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>8.0.20</version>
  </dependency>

  <!-- 连接池 HikariCP -->
  <dependency>
    <groupId>com.zaxxer</groupId>
    <artifactId>HikariCP</artifactId>
    <version>3.4.5</version>
  </dependency>

  <dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-simple</artifactId>
    <version>1.7.30</version>
  </dependency>
  <!-- ./连接池 HikariCP -->
  <!-- ./数据库相关 -->
  </dependencies>

</project>

配置

hikari.properties

jdbcUrl=jdbc:mysql://localhost:3306/test
username=root
password=root123
dataSource.cachePrepStmts=true
dataSource.prepStmtCacheSize=250
dataSource.prepStmtCacheSqlLimit=2048
dataSource.useServerPrepStmts=true
dataSource.useLocalSessionState=true
dataSource.rewriteBatchedStatements=true
dataSource.cacheResultSetMetadata=true
dataSource.cacheServerConfiguration=true
dataSource.elideSetAutoCommits=true
dataSource.maintainTimeStats=false

mybatis-config.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>
  <settings>
  <!-- 在控制台打印 SQL 语句及其结果集 -->
  <setting name="logImpl" value="STDOUT_LOGGING"/>
  </settings>
</configuration>
package net.wuxianjie.demo.config;

import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import org.apache.ibatis.session.ExecutorType;
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.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

@Configuration
@EnableTransactionManagement
@MapperScan("net.wuxianjie.demo.mapper")
public class DatabaseConfig {

  private static final String HIKARI_PROPERTIES_FILE_PATH = "/hikari.properties";

  @Bean
  public HikariDataSource hikariDataSource() {
  HikariConfig hikariConfig = new HikariConfig(HIKARI_PROPERTIES_FILE_PATH);
  return new HikariDataSource(hikariConfig);
  }

  @Bean
  public SqlSessionFactory sqlSessionFactory() throws Exception {
  ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver();

  SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
  sqlSessionFactoryBean.setDataSource(hikariDataSource());
  sqlSessionFactoryBean.setMapperLocations(
    resourcePatternResolver.getResources("classpath*:mappers/*SqlSessionFactoryBean */*.xml"));
  sqlSessionFactoryBean.setConfigLocation(
    resourcePatternResolver.getResource("classpath:mybatis-config.xml")
  );
  return sqlSessionFactoryBean.getObject();
  }

  @Bean
  public DataSourceTransactionManager transactionManager() {
  return new DataSourceTransactionManager(hikariDataSource());
  }

  @Bean
  public SqlSessionTemplate sqlSession() throws Exception {
  return new SqlSessionTemplate(sqlSessionFactory(), ExecutorType.BATCH);
  }
}

测试

package net.wuxianjie.demo.domain;

public class User {

  private Integer userId;

  private String userName;

  public Integer getUserId() {
  return userId;
  }

  public void setUserId(Integer userId) {
  this.userId = userId;
  }

  public String getUserName() {
  return userName;
  }

  public void setUserName(String userName) {
  this.userName = userName;
  }

  @Override
  public String toString() {
  return "User{" +
    "userId=" + userId +
    ", userName='" + userName + '\'' +
    '}';
  }
}
package net.wuxianjie.demo.mapper;

import net.wuxianjie.demo.domain.User;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

public interface UserMapper {

  //@Select("select user_id as userId, user_name as userName from login_user where user_id = #{id}")
  User selectUserById(@Param("id") Integer userId);
}

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="net.wuxianjie.demo.mapper.UserMapper">
  <select resultType="net.wuxianjie.demo.domain.User">
  select user_id as userId, user_name as userName from login_user where user_id = #{id}
  </select>
</mapper>
package net.wuxianjie.demo.service;

import net.wuxianjie.demo.domain.User;
import net.wuxianjie.demo.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserService {

  @Autowired
  private UserMapper userMapper;

  public User getUser(Integer userId) {
  return userMapper.selectUserById(userId);
  }
}
package net.wuxianjie.demo;

import net.wuxianjie.demo.service.UserService;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class Main {

  public static void main(String[] args) {
  AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext();
  applicationContext.scan("net.wuxianjie.demo");
  applicationContext.refresh();

  UserService userService = applicationContext.getBean("userService", UserService.class);
  System.out.println(userService.getUser(1));
  }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据

关于作者

倾城泪

暂无简介

0 文章
0 评论
530 人气
更多

推荐作者

安静被遗忘

文章 0 评论 0

喔爱吃橙子

文章 0 评论 0

草莓味的萝莉

文章 0 评论 0

梦里兽

文章 0 评论 0

mb_83J3Cyxa

文章 0 评论 0

时间海

文章 0 评论 0

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文