使用IDEA的gradle整合spring+ mybatis 採用javaconfig配置

1.新建一個工程java

2.工程目錄mysql

3.添加gradle.propertes文件git

activeMQVersion=5.7.0 aspectJVersion=1.7.2 commonsLangVersion = 3.1 ehcacheVersion=2.7.4 ehcacheJCacheVersion=1.4.0-beta1 h2Version=1.4.182 hamcrestVersion = 1.3 hibernateVersion=4.1.6.Final hibernateEntityManagerVersion=4.0.1.Final hibernateValidatorVersion = 5.0.1.Final jacksonVersion=2.4.3 javaxMailVersion=1.4.7 jspApiVersion = 2.1 jspElVersion = 2.2.4 jstlVersion = 1.2 junitVersion=4.12 log4jVersion=1.2.14 mockitoVersion=1.9.5 servletApiVersion = 3.1.0 slf4jVersion = 1.7.5 springAMQPVersion=1.0.0.RELEASE springDataJpaVersion=1.3.2.RELEASE springSecurityVersion = 3.2.0.RELEASE springVersion=4.0.7.RELEASE springWebflowVersion=2.4.1.RELEASE systemRulesVersion=1.5.0 thymeleafVersion = 2.1.3.RELEASE tilesVersion = 3.0.1 mysql_Java = 5.1.38 commons_dbcp = 1.4 mybatis_spring =1.2.5 mybatisVersion = 3.3.1

4.添加依賴,修改build.gradle文件github

group 'com.huang' version '1.0-SNAPSHOT' apply plugin: 'java' apply plugin: 'war' apply plugin: 'eclipse' apply plugin: 'idea' sourceCompatibility = 1.5 repositories { maven { url 'http://maven.springframework.org/release' } maven { url 'http://maven.springframework.org/milestone' } maven { url 'http://maven.springframework.org/snapshot' } maven { url 'http://download.java.net/maven/2' } mavenCentral() } dependencies { testCompile group: 'junit', name: 'junit', version: '4.12' testCompile"org.springframework:spring-test:${springVersion}" testCompile "com.github.stefanbirkner:system-rules:${systemRulesVersion}" compile "org.springframework:spring-core:$springVersion" compile "org.springframework:spring-context:$springVersion" compile "org.springframework:spring-jdbc:$springVersion" compile "org.mybatis:mybatis:$mybatisVersion" compile "org.mybatis:mybatis-spring:$mybatis_spring" compile "commons-dbcp:commons-dbcp:$commons_dbcp" compile "mysql:mysql-connector-java:$mysql_Java" compile "log4j:log4j:$log4jVersion" compile "com.h2database:h2:$h2Version" compile "javax.inject:javax.inject:1" compile "net.sf.ehcache:ehcache:$ehcacheVersion" compile "net.sf.ehcache:ehcache-jcache:$ehcacheJCacheVersion" }

5.執行sql腳本,建立數據庫表spring

SET FOREIGN_KEY_CHECKS=0; -- ---------------------------- -- Table structure for tbl_dep -- ----------------------------
DROP TABLE IF EXISTS `tbl_dep`; CREATE TABLE `tbl_dep` ( `depId` varchar(20) NOT NULL, `name` varchar(20) DEFAULT NULL, PRIMARY KEY (`depId`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- ---------------------------- -- Records of tbl_dep -- ----------------------------
INSERT INTO `tbl_dep` VALUES ('01', '總公司'); INSERT INTO `tbl_dep` VALUES ('0101', '一分公司'); INSERT INTO `tbl_dep` VALUES ('010101', '開發部'); INSERT INTO `tbl_dep` VALUES ('010102', '測試部'); INSERT INTO `tbl_dep` VALUES ('0102', '二分公司'); INSERT INTO `tbl_dep` VALUES ('010201', '開發部'); INSERT INTO `tbl_dep` VALUES ('010202', '測試部'); -- ---------------------------- -- Table structure for tbl_user -- ----------------------------
DROP TABLE IF EXISTS `tbl_user`; CREATE TABLE `tbl_user` ( `userId` varchar(20) NOT NULL, `name` varchar(20) DEFAULT NULL, `depId` varchar(20) NOT NULL, `sex` varchar(10) DEFAULT NULL, PRIMARY KEY (`userId`), KEY `TBL_USER_FK` (`depId`), CONSTRAINT `TBL_USER_FK` FOREIGN KEY (`depId`) REFERENCES `tbl_dep` (`depId`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- ---------------------------- -- Records of tbl_user -- ----------------------------
INSERT INTO `tbl_user` VALUES ('user0001', '張三1', '010101', ''); INSERT INTO `tbl_user` VALUES ('user0002', '張三2', '010101', ''); INSERT INTO `tbl_user` VALUES ('user0003', '張三3', '010102', ''); INSERT INTO `tbl_user` VALUES ('user0004', '張三4', '010201', ''); INSERT INTO `tbl_user` VALUES ('user0005', '張三5', '010201', ''); INSERT INTO `tbl_user` VALUES ('user0006', '張三6', '010102', ''); SET FOREIGN_KEY_CHECKS=1;

6.建立實體類User,對應tbl_user表sql

 

package com.huang.domain; /** * Created by huangyichun on 2016/12/9. */
public class User { private String userId; private String name; private String depId; private String sex; public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDepId() { return depId; } public void setDepId(String depId) { this.depId = depId; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } @Override public String toString() { return "User{" +
                "userId='" + userId + '\'' +
                ", name='" + name + '\'' +
                ", depId='" + depId + '\'' +
                ", sex='" + sex + '\'' +
                '}'; } }

7. 建立接口UserMapper,其中部分採用註解形式數據庫

package com.huang.mapper; import com.huang.domain.User; import org.apache.ibatis.annotations.Delete; import org.apache.ibatis.annotations.Param; import org.apache.ibatis.annotations.Select; import org.apache.ibatis.annotations.Update; import java.util.List; public interface UserMapper { @Select("SELECT * FROM tbl_user") List<User> getUserList(); @Select("SELECT * FROM tbl_user WHERE userId = #{userId}") User getUserById(@Param("userId") String userId); @Update("UPDATE tbl_user SET sex = #{sex} WHERE userId = #{userId}") void updateUserEmailById(@Param("userId") String userId, @Param("sex") String sex); @Delete("DELETE FROM tbl_user WHERE userId = #{userId}") void deleteUserById(@Param("userId") String userId); void insertUser(User user); }

8.建立UserMapper.xml文件,放在apache

若是放在java的com.huang.mapper文件夾下,將不會自動加載,這個Idea有關係session

 

9.建立配置類
mybatis

package com.huang.config; import org.apache.commons.dbcp.BasicDataSource; import org.mybatis.spring.SqlSessionFactoryBean; 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.jdbc.datasource.DataSourceTransactionManager; @Configuration @MapperScan(basePackages = "com.huang.mapper") public class DataConfig { @Bean public BasicDataSource dataSource(){ BasicDataSource dataSource = new BasicDataSource(); dataSource.setDriverClassName("com.mysql.jdbc.Driver"); dataSource.setUrl("jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8");//防止亂碼 dataSource.setUsername("root"); dataSource.setPassword("huangyichun"); dataSource.setInitialSize(5); dataSource.setMaxActive(10); return dataSource; } @Bean public DataSourceTransactionManager transactionManager() { return new DataSourceTransactionManager(dataSource()); } @Bean public SqlSessionFactoryBean sqlSessionFactory() throws Exception { SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean(); sessionFactory.setDataSource(dataSource()); sessionFactory.setTypeAliasesPackage("com.huang.domain"); sessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapper/*.xml")); return sessionFactory; } }

 

10.建立測試類

import com.huang.config.DataConfig; import com.huang.domain.User; import com.huang.mapper.UserMapper; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import java.util.List; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = DataConfig.class) public class TestMybatis { @Autowired private UserMapper userMapper; @Test public void getUserById(){ User user = userMapper.getUserById("user0005"); System.out.println(user.toString()); } @Test public void getUserList(){ List<User> list = userMapper.getUserList(); for (User user : list){ System.out.println(user.toString()); } } @Test public void updateUserEmailById(){ userMapper.updateUserEmailById("user0006","女"); } @Test public void deleteUserById(){ userMapper.deleteUserById("user0006"); } @Test public void insertUser(){ User user = new User(); user.setUserId("user0008"); user.setName("張三7"); user.setDepId("010102"); user.setSex("男"); userMapper.insertUser(user); } }
相關文章
相關標籤/搜索