MyBatis-Spring 整合 Spring Core
目录结构:
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 技术交流群。
上一篇: 唯一索引 vs 主键索引
下一篇: 不要相信一个熬夜的人说的每一句话
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论