spring 集成 mybatis的實(shí)例詳解
環(huán)境配置
1>先創(chuàng)建maven的quickstart項(xiàng)目;并且創(chuàng)建dao層,service層,controller層,po層,mapper,resources以及下面的配置文件(db.properties,log4j.properties,mybatis.xml,spring.xml).
2>配置pom.xml
修改jdk版本;
添加依賴:
junit版本改為4.12;spring-context;spring-test;spring-jdbc;spring-tx(事務(wù));aspectjweaver(切面編程);c3p0(連接池);mybatis;mybatis-spring;mysql-connector-java(mysql驅(qū)動(dòng)包);slf4j-log4j12,slf4j-api(日志打印);
設(shè)置資源目錄和插件
<build> <!-- Maven 項(xiàng)目:如果源代碼(src/main/java)存在xml、properties、tld 等文件 Maven 默認(rèn)不會(huì)自動(dòng)編譯該文件到輸出目錄,如果要編譯源代碼中xml properties tld 等文件 需要顯式配置 resources 標(biāo)簽 --> <resources> <resource> <directory>src/main/resources</directory> </resource> <resource> <directory>src/main/java</directory> <includes> <include>**/*.xml</include> <include>**/*.properties</include> <include>**/*.tld</include> </includes> <filtering>false</filtering> </resource> </resources> </build>
3>配置spring.xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd"> <!-- 掃描基本包 --> <context:component-scan base-package="com.xxxx" /> <!-- 加載properties 配置文件 --> <context:property-placeholder location="classpath:db.properties" /> <!-- aop --> <aop:aspectj-autoproxy /> <!-- 配置c3p0 數(shù)據(jù)源 --> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <property name="driverClass" value="${jdbc.driver}"></property> <property name="jdbcUrl" value="${jdbc.url}"></property> <property name="user" value="${jdbc.username}"></property> <property name="password" value="${jdbc.password}"></property> </bean> <!-- 配置事務(wù)管理器 --> <bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource"></property> </bean> <!-- 設(shè)置事物增強(qiáng) --> <tx:advice id="txAdvice" transaction-manager="txManager"> <tx:attributes> <tx:method name="add*" propagation="REQUIRED" /> <tx:method name="insert*" propagation="REQUIRED" /> <tx:method name="update*" propagation="REQUIRED" /> <tx:method name="delete*" propagation="REQUIRED" /> </tx:attributes> </tx:advice> <!-- aop 切面配置 --> <aop:config> <aop:pointcut id="servicePointcut" expression="execution(* com.xxxx.service..*.*(..))" /> <aop:advisor advice-ref="txAdvice" pointcut-ref="servicePointcut" /> </aop:config> <!-- 配置 sqlSessionFactory --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource"></property> <property name="configLocation" value="classpath:mybatis.xml" /> <property name="mapperLocations" value="classpath:com/xxxx/mapper/*.xml" /> </bean> <!-- 配置掃描器 --> <bean id="mapperScanner" class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <!-- 掃描com.xxxx.dao這個(gè)包以及它的子包下的所有映射接口類 --> <property name="basePackage" value="com.xxxx.dao" /> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" /> </bean> </beans>
4>配置 mybatis.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> <!-- 定義類別名 --> <typeAliases> <package name="com.xxxx.po"/> </typeAliases> </configuration>
5>配置 db.properties
jdbc.url中?前面的spring_mybatis是數(shù)據(jù)庫(kù)名字,注意要修改下
password是密碼,也是要修改下的
6>添加日志
jdbc.driver=com.mysql.cj.jdbc.Driver jdbc.url=jdbc:mysql://localhost:3306/spring_mybatis? useUnicode=true&characterEncoding=utf8&serverTimezone=GMT%2B8&useSSL=false jdbc.username=root jdbc.password=root
log4j.properties
log4j.rootLogger=DEBUG, Console # Console log4j.appender.Console=org.apache.log4j.ConsoleAppender log4j.appender.Console.layout=org.apache.log4j.PatternLayout log4j.appender.Console.layout.ConversionPattern=%d [%t] %-5p [%c] - %m%n log4j.logger.java.sql.ResultSet=INFO log4j.logger.org.apache=INFO log4j.logger.java.sql.Connection=DEBUG log4j.logger.java.sql.Statement=DEBUG log4j.logger.java.sql.PreparedStatement=DEBUG
添加源代碼
1>在po 包下創(chuàng)建 JavaBean 文件 User.java
public class User { private Integer userId; private String userName; private String userPwd; private String userEmail; private Date createDate; private Date updateDate; /** set get toString 方法省略 **/ }
2>在dao層添加UserDao接口
public interface UserDao { User queryUserByUserId(Integer userId); }
3>在mapper包添加UserMapper.xml 映射文件
sql代碼寫(xiě)在這地方
<?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.xxxx.dao.UserDao"> <select id="queryUserByUserId" parameterType="int" resultType="com.xxxx.po.User"> select user_id as userId,user_name as userName,user_pwd as userPwd from tb_user where user_id = #{userId} </select> </mapper>
4>添加 UserService.java
@Service public class UserService { @Autowired private UserDao userDao; public User queryUserByUserId(Integer userId){ return userDao.queryUserByUserId(userId); } }
5>添加 UserController.java
@Controller public class UserController { // 注入userService @Resource private UserService userService; /** * 通過(guò)用戶ID查詢用戶對(duì)象 * @param userId * @return */ public User queryUserByUserId(Integer userId) { User user = userService.queryUserByUserId(userId); return user; } }
執(zhí)行測(cè)試
public class App { public static void main(String[] args) { // 加載Spring的配置 BeanFactory factory = new ClassPathXmlApplicationContext("spring.xml"); // 得到UserController對(duì)象 UserController userController = (UserController) factory.getBean("userController"); // 調(diào)用方法 User user = userController.queryUserByUserId(1); System.out.println(user.toString()); } }
到此這篇關(guān)于spring 集成 mybatis的文章就介紹到這了,更多相關(guān)spring 集成 mybatis內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Java實(shí)現(xiàn)按權(quán)重隨機(jī)數(shù)
這篇文章主要介紹了Java實(shí)現(xiàn)按權(quán)重隨機(jī)數(shù),本文給出了提出問(wèn)題、分析問(wèn)題、解決問(wèn)題三個(gè)步驟,需要的朋友可以參考下2015-04-04MyBatis實(shí)現(xiàn)多表聯(lián)合查詢r(jià)esultType的返回值
這篇文章主要介紹了MyBatis多表聯(lián)合查詢r(jià)esultType的返回值,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-03-03Spring Boot利用Thymeleaf發(fā)送Email的方法教程
spring Boot默認(rèn)就是使用thymeleaf模板引擎的,下面這篇文章主要給大家介紹了關(guān)于在Spring Boot中利用Thymeleaf發(fā)送Email的方法教程,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面來(lái)一起看看吧。2017-08-08Java基于JDBC連接數(shù)據(jù)庫(kù)及顯示數(shù)據(jù)操作示例
這篇文章主要介紹了Java基于JDBC連接數(shù)據(jù)庫(kù)及顯示數(shù)據(jù)操作,結(jié)合實(shí)例形式分析了Java使用jdbc進(jìn)行mysql數(shù)據(jù)庫(kù)連接與數(shù)據(jù)讀取、顯示等相關(guān)操作技巧,需要的朋友可以參考下2018-06-06Java CountDownLatch與CyclicBarrier及Semaphore使用教程
對(duì)于并發(fā)執(zhí)行,Java中的CountDownLatch是一個(gè)重要的類。為了更好的理解CountDownLatch這個(gè)類,本文將通過(guò)例子和源碼帶領(lǐng)大家深入解析CountDownLatch與CyclicBarrier及Semaphore的原理,感興趣的可以學(xué)習(xí)一下2023-01-01Java實(shí)用技巧:如何使用String去除開(kāi)頭的第一個(gè)字符?
這篇文章主要介紹了Java實(shí)用技巧:如何使用String去除開(kāi)頭的第一個(gè)字符,需要的朋友可以參考下2023-11-11SpringBoot-RestTemplate如何實(shí)現(xiàn)調(diào)用第三方API
這篇文章主要介紹了SpringBoot-RestTemplate實(shí)現(xiàn)調(diào)用第三方API的操作,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-08-08解決使用ProcessBuilder踩到的坑及注意事項(xiàng)
這篇文章主要介紹了解決使用ProcessBuilder踩到的坑,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-06-06