搜索词>>spring boot mybaties 整合 耗时0.2070
  • spring boot mybatis 整合_spring boot mybatis3 事物配置

    spring boot mybatis 整合过程中事物得配置详细讲解,spring boot mybatis3 事物配置详细讲解<h2>引言</h2>     通过之前spring boot mybatis 整合的讲解: <blockquote> <a rel="" target="_blank"href="http://www.leftso.com/blog/80.html" rel="" target="_blank" title="spring boot整合mybaties">spring boot mybaties整合  </a>(spring boot mybaties 整合 基于Java注解方式写sql,无需任何得mapper xml文件) <p><a rel="" target="_blank"href="http://www.leftso.com/blog/133.html" rel="" target="_blank" title="spring boot mybatis 整合_spring boot与mybaties的使用">spring boot mybatis 整合_spring boot与mybaties的使用</a>  (spring boot mybaties 整合 xml mapper方式,也是实际应用最多得方式)</p> </blockquote> 我们对于spring boot mybaties 整合有了一个基础的认知。这里主要正对上面得两篇文章中spring boot mybaties整合讲解得一个扩展学习,事物的配置,整合到spring 的事物控制中。 <h2>一.环境准备</h2> 本博客讲沿用上面的项目进行进一步讲解 <h2>二.实战编码</h2> <h3>2.1 spring boot 核心配置文件application.properties</h3> <pre> <code class="language-html">#==================DataSource Config Start================== #默认采用Tomcat-jdbc-pool性能和并发最好,注意查看maven依赖中是否有tomcat-jdbc #name #spring.datasource.name=test #url #spring.datasource.url=jdbc:sqlserver://192.168.xxx.xxx;instanceName=sql_03;DatabaseName=edu;integratedSecurity=false spring.datasource.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8 #DriverClass #spring.datasource.driver-class-name=com.microsoft.sqlserver.jdbc.SQLServerDriver spring.datasource.tomcat.driver-class-name=com.mysql.jdbc.Driver #DB username spring.datasource.tomcat.username=root #DB password spring.datasource.tomcat.password=root #最大连接数量 spring.datasource.tomcat.max-active=150 #最大闲置连接数量 spring.datasource.tomcat.max-idle=20 #最大等待时间 #spring.datasource.tomcat.max-wait=5000 #==================DataSource Config End================== #==================mybaties Config Start================== #ORM Bean Package mybatis.type-aliases-package=com.example.pojo mybatis.mapper-locations=classpath:/mapper/*.xml #打印mybatiesSql语句 logging.level.com.example.mapper=DEBUG #==================mybaties Config End ================== #模板引擎配置缓存为FALSE。开发调试用 spring.thymeleaf.cache=false </code></pre> 这里注意关注数据连接配置和mybaties的xml mapper文件配置。<br />   <h3>2.2spring boot mybaties 整合 事物关键配置</h3> <strong>MyBatiesConfig.java</strong> <pre> <code class="language-java">package com.example.config; import javax.sql.DataSource; import org.mybatis.spring.annotation.MapperScan; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.jdbc.datasource.DataSourceTransactionManager; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.annotation.EnableTransactionManagement; /** * mybaties配置扫描mapper路径 * * @author leftso * */ @Configuration @MapperScan(basePackages = { "com.example.mapper" }) /** 注意,这个注解是扫描mapper接口不是xml文件,使用xml模式必须在配置文件中添加xml的配置 **/ @EnableTransactionManagement /** * 启用事物管理 ,在需要事物管理的service类或者方法上使用注解@Transactional **/ public class MyBatiesConfig { @Autowired private DataSource dataSource; /** * 配合注解完成事物管理 * * @return */ @Bean public PlatformTransactionManager annotationDrivenTransactionManager() { return new DataSourceTransactionManager(dataSource); } } </code></pre> 注意必须把当前的数据源配置进入spring的注解事物管理器。否则通过spring框架的注解标签@Transactional是不会有事物作用的。<br />   <h2>三.事物演示</h2> <h3>3.1编写测试代码</h3> <pre> <code class="language-java">package com.example.test; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; import com.example.mapper.UserMapper; import com.example.pojo.User; @RunWith(SpringRunner.class) @SpringBootTest public class TransactionalTest { @Autowired private UserMapper userMapper; @Test public void name() { User user=new User("leftso", "男", 1); userMapper.insert(user); int t=1/0; System.out.println(t); } } </code></pre> 执行前查询数据库:<br /> <img alt="执行前查询数据库:" class="img-thumbnail" src="/resources/assist/images/blog/5f8c20ca282f4b1c855725c473a0a5ff.png" /><br /> 执行测试代码并观察eclipse的控制台和数据库的数据查询结果:<br /> <img alt="eclipse的控制台" class="img-thumbnail" src="/resources/assist/images/blog/552fd284c5b04a03ab408b68f7e56532.png" /><br /> <img alt="数据库查询结果" class="img-thumbnail" src="/resources/assist/images/blog/55507a3964bb4482b00c9a6bd95b2f75.png" /><br /> 很明显在报错的情况下,数据还是插入进了数据库。这并不是我们正常业务想要的结果。 <h3>3.2编辑测试代码,添加spring框架的事物注解</h3> <pre> <code class="language-java">package com.example.test; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.transaction.annotation.Transactional; import com.example.mapper.UserMapper; import com.example.pojo.User; @RunWith(SpringRunner.class) @SpringBootTest public class TransactionalTest { @Autowired private UserMapper userMapper; @Test @Transactional public void name() { User user=new User("测试哈哈", "女", 2); userMapper.insert(user); int t=1/0; System.out.println(t); } } </code></pre> <br /> 执行代码并观察eclipse和数据库:<br /> <img alt="spring boot mybaties 整合测试eclipse控制台输出结果" class="img-thumbnail" src="/resources/assist/images/blog/db0656c4eb684dfaad995363bf77a6ac.png" /><br /> <br /> <img alt="spring boot mybaties 整合 测试数据库查询结果" class="img-thumbnail" src="/resources/assist/images/blog/479ffa98d4a64ef888e6cf6654e0f956.png" /><br /> <br /> 这次的操作姿势似乎对了。在报错的情况下数据并没有插入数据库。我们仔细观察spring 控制台输出的日志可以发现事物已经在spring的控制下回滚了。<br /> <img alt="spring boot mybaties 整合 测试异常回滚eclipse控制台日志输出结果" class="img-thumbnail" src="/resources/assist/images/blog/f2e785539cff4ef7b04a86253f94ac00.png" /><br /> 从上图也可以看到回滚的日志<br />  
  • spring boot整合mybaties

    spring boot框架整合mybaties数据库暂时选用MySQL<br /> 本博文主要讲解spring boot项目整合mybaties<br /> 1.最终项目结构图<br /> <img alt="结构" class="img-thumbnail" src="/resources/assist/images/blog/e0b0519f-a4be-43fe-aabe-d57927ba82b5.jpg" style="height:564px; width:305px" /><br /> 2.文件清单<br /> 清单:pom.xml <pre> <code class="language-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>com.example</groupId> <artifactId>demo-springboot-mybaties</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>demo-springboot-mybaties</name> <description>Demo project for Spring Boot</description> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.1.RELEASE</version> <relativePath /> <!-- lookup parent from repository --> </parent> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <java.version>1.8</java.version> </properties> <dependencies> <!-- mybaties --> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>1.2.0</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <!-- mysql驱动 --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project> </code></pre> 清单:User.java <pre> <code class="language-java">package com.example.pojo; public class User { private Long id; private String userName; private String userSex; private int userAge; public User() { } public User(String userName, String userSex, int userAge) { super(); this.userName = userName; this.userSex = userSex; this.userAge = userAge; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getUserSex() { return userSex; } public void setUserSex(String userSex) { this.userSex = userSex; } public int getUserAge() { return userAge; } public void setUserAge(int userAge) { this.userAge = userAge; } } </code></pre> 清单:UserMapper.java <pre> <code class="language-java">package com.example.mapper; import java.util.List; import org.apache.ibatis.annotations.Delete; import org.apache.ibatis.annotations.Insert; import org.apache.ibatis.annotations.Param; import org.apache.ibatis.annotations.Result; import org.apache.ibatis.annotations.Results; import org.apache.ibatis.annotations.Select; import org.apache.ibatis.annotations.Update; import com.example.pojo.User; public interface UserMapper { /** * 查询所有用户信息 * * @return */ @Select("select * from user") @Results(value = { @Result(property = "userSex", column = "user_sex", javaType = String.class), @Result(property = "userName", column = "user_name"), @Result(property = "userAge", column = "user_age") }) List<User> findList(); /** * 通过ID查询 * * @param id * @return */ @Select("select * from user u where u.id=#{id}") User findOne(@Param("id") Long id); /** * 新增一个 * * @param user */ @Insert("insert into user (user_name,user_sex,user_age) values(#{userName},#{userSex},#{userAge})") void insert(User user); /** * 修改 * * @param user */ @Update("update user u set u.user_name=#{userName},u.user_sex=#{userSex},u.user_age=#{userAge} where u.id=#{id}") void update(User user); /** * 删除 * * @param id */ @Delete("delete from user where id=#{id}") void delete(@Param("id") Long id); } </code></pre> 清单:UserController.java <pre> <code class="language-java">package com.example.controller; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.example.mapper.UserMapper; import com.example.pojo.User; @RestController public class UserController { @Autowired UserMapper userMapper; /** * index * * @return */ @RequestMapping("/") public String index() { return "User Info By Mybaties"; } @RequestMapping("/user/list.json") public Object allUsers() { List<User> users = userMapper.findList(); return users; } } </code></pre> 清单:Application.java <pre> <code class="language-java">package com.example; import org.mybatis.spring.annotation.MapperScan; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.transaction.annotation.EnableTransactionManagement; @SpringBootApplication @MapperScan(basePackages = { "com.example.mapper" }) // 自动扫描mapper @EnableTransactionManagement//启用事物管理,在service上使用@Transactional(注意是spring的 注解) public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } } </code></pre> 清单:application.properties <pre> <code class="language-perl">#==================DataSource Config Start================== #name #spring.datasource.name=test #url #spring.datasource.url=jdbc:sqlserver://192.168.xxx.xxx;instanceName=sql_03;DatabaseName=edu;integratedSecurity=false spring.datasource.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8 #DriverClass #spring.datasource.driver-class-name=com.microsoft.sqlserver.jdbc.SQLServerDriver spring.datasource.driver-class-name=com.mysql.jdbc.Driver #DB username spring.datasource.username=root #DB password spring.datasource.password=root #==================DataSource Config End================== #==================mybaties Config Start================== #ORM Bean Package mybatis.type-aliases-package=com.example.pojo mybatis.mapper-locations=classpath:/mapper/*.xml #打印mybatiesSql语句 logging.level.com.example.mapper=DEBUG #==================mybaties Config End ================== </code></pre> 清单:UserMapperTest.java <pre> <code class="language-java">package com.example.test; import java.util.List; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; import com.example.mapper.UserMapper; import com.example.pojo.User; @RunWith(SpringRunner.class) @SpringBootTest public class UserMapperTest { @Autowired private UserMapper userMapper; // @Test public void testInsert() { try { userMapper.insert(new User("xqlee1", "男", 26)); userMapper.insert(new User("xqlee2", "男", 23)); userMapper.insert(new User("xqlee3", "男", 27)); } catch (Exception e) { e.printStackTrace(); } } // @Test public void testUpdate() { try { User user = new User("测试0000", "男", 23); user.setId(1l); userMapper.update(user); } catch (Exception e) { e.printStackTrace(); } } //@Test public void testQuery() { try { List<User> users=userMapper.findList(); for(User u:users){ System.out.println("ID:"+u.getId()+" Name:"+u.getUserName()+" Sex:"+u.getUserSex()+" Age:"+u.getUserAge()); } } catch (Exception e) { e.printStackTrace(); } } @Test public void testDelete(){ try { userMapper.delete(1l); testQuery(); } catch (Exception e) { e.printStackTrace(); } } } </code></pre>
  • spring boot mybatis 整合_spring boot与mybaties的使用

    spring boot mybatis 整合使用讲解介绍,spring boot与mybaties的使用讲解介绍。spring boot mybatis xml mapper方式的入门和通过一个简单的例子带新手入门spring boot整合mybaties基本使用。本文主要讲解在Java编程中,spring boot mybatis xml mapper方式的入门和通过一个简单的例子带新手入门mybaties基本使用。<br /> 项目结构图: <div><img alt="项目结构图" class="img-thumbnail" src="/resources/assist/images/blog/fcb23b60-db2a-4cb6-b44f-663c8ed9c4ea.png" /><br /> 项目结构图<br /> <br /> 代码清单:<br /> <br /> spring boot配置文件application.properties: <pre> <code>#==================DataSource Config Start================== #name #spring.datasource.name=test #url #spring.datasource.url=jdbc:sqlserver://192.168.xxx.xxx;instanceName=sql_03;DatabaseName=edu;integratedSecurity=false spring.datasource.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8 #DriverClass #spring.datasource.driver-class-name=com.microsoft.sqlserver.jdbc.SQLServerDriver spring.datasource.driver-class-name=com.mysql.jdbc.Driver #DB username spring.datasource.username=root #DB password spring.datasource.password=root #==================DataSource Config End================== #==================mybaties Config Start================== #ORM Bean Package mybatis.type-aliases-package=com.leftso.pojo mybatis.mapper-locations=classpath:/mapper/*.xml #==================mybaties Config End ==================</code></pre> </div> <br /> spring boot log简单配置,用于打印sql日志logback-spring.xml: <pre> <code class="language-xml"><?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE configuration> <configuration> <include resource="org/springframework/boot/logging/logback/base.xml" /> <!-- 打印sql --> <logger name="com.leftso.mapper" level="DEBUG" /> </configuration></code></pre> <br /> <br /> mybaties Java config 配置MyBatiesConfig.java: <pre> <code class="language-java">package com.leftso.config; import org.mybatis.spring.annotation.MapperScan; import org.springframework.context.annotation.Configuration; /** * mybaties配置扫描mapper路径 * * @author leftso * */ @Configuration @MapperScan(basePackages = { "com.leftso.mapper" }) /** 注意,这个注解是扫描mapper接口不是xml文件,使用xml模式必须在配置文件中添加xml的配置 **/ public class MyBatiesConfig { } </code></pre> <br /> 简单测试的用户pojo对象User.java: <pre> <code class="language-java">package com.leftso.pojo; /** * 用户 * * @author leftso * */ public class User { private Long id; private String userName; private int age; private String sex; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } } </code></pre> <br /> User对象的mapper接口:UserMapper.java: <pre> <code class="language-java">package com.leftso.mapper; import java.util.List; import java.util.Map; import org.springframework.stereotype.Component; import com.leftso.pojo.User; @Component("userMapper") public interface UserMapper { // 新增 int add(User user); // 修改 int remove(Long id); // 删除 int update(User user); // 查一个 User findOne(Long id); // 查多个 List<User> findList(Map<String, Object> params); } </code></pre> <br /> mapper对应的xml文件UserMapper.xml: <pre> <code class="language-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.leftso.mapper.UserMapper"> <!-- 创建一个数据库user表与java中user对象关联的返回映射map --> <resultMap type="com.leftso.pojo.User" id="UserMap"> <id column="id" property="id" jdbcType="NUMERIC" /> <result column="user_name" property="userName" jdbcType="VARCHAR" /> <result column="age" property="age" jdbcType="NUMERIC" /> <result column="sex" property="sex" jdbcType="VARCHAR" /> </resultMap> <!-- 新增 --> <insert id="add" parameterType="com.leftso.pojo.User" useGeneratedKeys="true" keyProperty="id"> insert into t_user <trim prefix="(" suffix=")" suffixOverrides=","><!-- 说明:使用trim的方式组合sql,属性suffixOverrides表示去除末端多余的该属性值(这里是,) --> user_name, age, sex </trim> <trim prefix="values (" suffix=")" suffixOverrides=","> #{name,jdbcType=VARCHAR}, #{age,jdbcType=NUMERIC},<!-- 说明:数字类型都是NUMERIC,没有INT,LONG类型;其他对应类型请参照mybaties官方文档 --> #{sex,jdbcType=VARCHAR} </trim> </insert> <!-- 删除 --> <delete id="remove" parameterType="java.lang.Long"> delete from t_user where id=#{id} </delete> <!-- 修改属性 --> <update id="update" parameterType="com.leftso.pojo.User"> update t_user <set> <trim suffixOverrides=","> <if test="null!=name and ''!=name"> user_name=#{name,jdbcType=VARCHAR}, </if> <if test="null!=age"> age=#{age,jdbcType=NUMERIC}, </if> <if test="null!=sex and ''!= sex"> sex=#{sex,jdbcType=VARCHAR}, </if> </trim> </set> where id=#{id,jdbcType=NUMERIC} </update> <!-- 查询一个 --> <select id="findOne" parameterType="java.lang.Long" resultMap="UserMap"> select * from t_user where id=#{id} </select> <!-- 查询多个 --> <select id="findList" parameterType="java.util.Map" resultMap="UserMap"> select * from t_user where 1=1 <if test="null!=name and '' != name"> and user_name like '%${name}%' </if> <if test=" sex != null and '' != sex"> and sex = #{sex} </if> <if test="age > 0"> and age <![CDATA[ >=]]>#{age} <!-- 说明:在xml里面大于小于大于等于需要逆转 --> </if> </select> </mapper></code></pre> <br /> 单元测试类: <pre> <code class="language-java">package com.leftso; import java.util.HashMap; import java.util.List; import java.util.Map; import org.junit.Test; import org.junit.runner.RunWith; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; import com.leftso.mapper.UserMapper; import com.leftso.pojo.User; @RunWith(SpringRunner.class) @SpringBootTest public class ApplicationTests { Logger log = LoggerFactory.getLogger(getClass()); @Autowired UserMapper userMapper; // @Test public void add() { try { User user = new User(); user.setUserName("测试用户名"); user.setAge(25); user.setSex("男"); log.info("新增前ID:" + user.getId()); userMapper.add(user); log.info("新增后ID:" + user.getId()); } catch (Exception e) { e.printStackTrace(); } } // @Test public void remove() { try { userMapper.remove(2l); } catch (Exception e) { e.printStackTrace(); } } // @Test public void update() { try { User user = new User(); user.setId(3l); user.setUserName("我是修改"); user.setAge(2); userMapper.update(user); } catch (Exception e) { e.printStackTrace(); } } // @Test public void findOne() { try { User user = userMapper.findOne(3l); log.info("\nName:" + user.getUserName() + "\nAge:" + user.getAge() + "\nSex:" + user.getSex()); } catch (Exception e) { e.printStackTrace(); } } @Test public void findList() { try { Map<String, Object> params = new HashMap<String, Object>(); params.put("name", "我"); params.put("age", 3); List<User> list = userMapper.findList(params); for (User user : list) { log.info("\nName:" + user.getUserName() + "\nAge:" + user.getAge() + "\nSex:" + user.getSex()); } } catch (Exception e) { e.printStackTrace(); } } } </code></pre> <br /> 源码下载:<br /> GitHub:<a href="https://github.com/leftso/demo-spring-boot-mybaties3" rel="external nofollow" target="_blank">https://github.com/leftso/demo-spring-boot-mybaties3</a>
  • spring boot 1.5.2整合mybaties日志打印出sql语句

    本文主要讲解spring boot框架整合mybaties后,如何打印出mybaties的sql语句以及参数列表本文主要讲解spring boot框架整合mybaties后,如何打印出mybaties的sql语句以及参数列表<br /> 其实办法很简单<br /> 在springboot项目中有一个application.properties属性配置文件,在该配置文件中加入以下代码即可 <pre> <code>logging.level.com.leftso.mapper=DEBUG</code></pre> <br /> <span style="color:#1abc9c">解释:<br /> 其中只需要将com.leftso.mapper改为你自己的mapper接口存放的包路径就OK</span>
  • spring boot mybaties 配置多数据源

    spring boot mybaties 配置多数据源<h2>引言</h2> <blockquote> <p>说起多数据源,一般都来解决那些问题呢,主从模式或者业务比较复杂需要连接不同的分库来支持业务。我们项目是后者的模式,网上找了很多,大都是根据jpa来做多数据源解决方案,要不就是老的spring多数据源解决方案,还有的是利用aop动态切换,感觉有点小复杂,其实我只是想找一个简单的多数据支持而已,折腾了两个小时整理出来,供大家参考。</p> </blockquote> <h2>配置文件</h2> pom.xml<br /> 参考之前写的一篇<a rel="" target="_blank"href="http://www.leftso.com/blog/133.html" rel="" target="_blank" title="spring boot mybatis 整合_spring boot与mybaties的使用">spring boot mybatis 整合_spring boot与mybaties的使用</a><br /> <br /> 主要是数据库这边的配置: <pre> <code class="language-html">#mybatis其他配置可选 mybatis.config-locations=classpath:mybatis/mybatis-config.xml spring.datasource.test1.driverClassName = com.mysql.jdbc.Driver spring.datasource.test1.url = jdbc:mysql://localhost:3306/test1?useUnicode=true&characterEncoding=utf-8 spring.datasource.test1.username = root spring.datasource.test1.password = root spring.datasource.test2.driverClassName = com.mysql.jdbc.Driver spring.datasource.test2.url = jdbc:mysql://localhost:3306/test2?useUnicode=true&characterEncoding=utf-8 spring.datasource.test2.username = root spring.datasource.test2.password = root</code></pre> 一个test1库和一个test2库,其中test1位主库,在使用的过程中必须制定主库,不然会报错。 <h2>数据源配置</h2> <pre> <code class="language-java">@Configuration@MapperScan(basePackages = "com.neo.mapper.test1", sqlSessionTemplateRef = "test1SqlSessionTemplate") public class DataSource1Config { @Bean(name = "test1DataSource") @ConfigurationProperties(prefix = "spring.datasource.test1") @Primary public DataSource testDataSource() { return DataSourceBuilder.create().build(); } @Bean(name = "test1SqlSessionFactory") @Primary public SqlSessionFactory testSqlSessionFactory(@Qualifier("test1DataSource") DataSource dataSource) throws Exception { SqlSessionFactoryBean bean = new SqlSessionFactoryBean(); bean.setDataSource(dataSource); bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mybatis/mapper/test1/*.xml")); return bean.getObject(); } @Bean(name = "test1TransactionManager") @Primary public DataSourceTransactionManager testTransactionManager(@Qualifier("test1DataSource") DataSource dataSource) { return new DataSourceTransactionManager(dataSource); } @Bean(name = "test1SqlSessionTemplate") @Primary public SqlSessionTemplate testSqlSessionTemplate(@Qualifier("test1SqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception { return new SqlSessionTemplate(sqlSessionFactory); } }</code></pre> <p>最关键的地方就是这块了,一层一层注入,先创建DataSource,在创建SqlSessionFactory在创建事务,最后包装到SqlSessionTemplate中。其中需要制定分库的mapper文件地址,以及分库到层代码</p> <pre> <code class="language-java">@MapperScan(basePackages = "com.neo.mapper.test1", sqlSessionTemplateRef  = "test1SqlSessionTemplate")</code></pre> <p>这块的注解就是指明了扫描dao层,并且给dao层注入指定的SqlSessionTemplate。所有<code>@Bean</code>都需要按照命名指定正确。</p> <h2>dao层和xml层</h2> dao层和xml需要按照库来分在不同的目录,比如:test1库dao层在com.neo.mapper.test1包下,test2库在com.neo.mapper.test1 <pre> <code class="language-java">public interface User1Mapper {      List<UserEntity> getAll();        UserEntity getOne(Long id);    void insert(UserEntity user);    void update(UserEntity user);        void delete(Long id); }</code></pre> <p>xml层</p> <pre> <code class="language-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.neo.mapper.test1.User1Mapper" >    <resultMap id="BaseResultMap" type="com.neo.entity.UserEntity" >        <id column="id" property="id" jdbcType="BIGINT" />        <result column="userName" property="userName" jdbcType="VARCHAR" />        <result column="passWord" property="passWord" jdbcType="VARCHAR" />        <result column="user_sex" property="userSex" javaType="com.neo.enums.UserSexEnum"/>        <result column="nick_name" property="nickName" jdbcType="VARCHAR" />    </resultMap>    <sql id="Base_Column_List" >        id, userName, passWord, user_sex, nick_name        </sql>    <select id="getAll" resultMap="BaseResultMap"  >       SELECT       <include refid="Base_Column_List" />       FROM users        </select>    <select id="getOne" parameterType="java.lang.Long" resultMap="BaseResultMap" >        SELECT       <include refid="Base_Column_List" />       FROM users       WHERE id = #{id}        </select>    <insert id="insert" parameterType="com.neo.entity.UserEntity" >       INSERT INTO            users            (userName,passWord,user_sex)        VALUES            (#{userName}, #{passWord}, #{userSex})        </insert>    <update id="update" parameterType="com.neo.entity.UserEntity" >       UPDATE            users       SET        <if test="userName != null">userName = #{userName},</if>        <if test="passWord != null">passWord = #{passWord},</if>        nick_name = #{nickName}       WHERE            id = #{id}         </update>    <delete id="delete" parameterType="java.lang.Long" >       DELETE FROM             users       WHERE             id =#{id}       </delete>   </mapper></code></pre> <h2>测试</h2> <p>测试可以使用SpringBootTest,也可以放到Controller中,这里只贴Controller层的使用</p> <pre> <code class="language-java">@RestControllerpublic class UserController {        @Autowired    private User1Mapper user1Mapper;            @Autowired    private User2Mapper user2Mapper;            @RequestMapping("/getUsers")        public List<UserEntity> getUsers() {        List<UserEntity> users=user1Mapper.getAll();        return users;    }            @RequestMapping("/getUser")        public UserEntity getUser(Long id) {        UserEntity user=user2Mapper.getOne(id);                return user;    }            @RequestMapping("/add")        public void save(UserEntity user) {        user2Mapper.insert(user);    }            @RequestMapping(value="update")        public void update(UserEntity user) {        user2Mapper.update(user);    }            @RequestMapping(value="/delete/{id}")        public void delete(@PathVariable("id") Long id) {        user1Mapper.delete(id);    } }</code></pre>
  • springMVC4+Spring4+Mybaties3项目整合简单例子

    本文章主要简单讲解目前流行的springMVC4+Spring4+Mybaties3(即SSM)框架整合<h2>一.创建一个web的maven项目</h2> 项目完整结构图:<br /> <img alt="项目结构" class="img-thumbnail" src="/resources/assist/images/blog/27a2fcf7-752b-47b6-800a-99fad6608711.png" style="height:911px; width:457px" /> <h2> 二.相关文件内容</h2> <br />  1.pom.xml <pre> <code class="language-xml"><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/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.xqlee.dev.project.ssm</groupId> <artifactId>demo-ssm</artifactId> <packaging>war</packaging> <version>0.0.1-SNAPSHOT</version> <name>demo-ssm Maven Webapp</name> <url>http://maven.apache.org</url> <profiles> <profile> <id>jdk-1.8</id> <!-- 另外一种激活方式 --> <activation> <activeByDefault>true</activeByDefault> <jdk>1.8</jdk> </activation> <properties> <maven.compiler.source>1.8</maven.compiler.source> <maven.compiler.target>1.8</maven.compiler.target> <maven.compiler.compilerVersion>1.8</maven.compiler.compilerVersion> <com.fasterxml.jackson.jaxrs.version>2.4.1</com.fasterxml.jackson.jaxrs.version> </properties> </profile> </profiles> <!-- 属性版本 --> <properties> <junit.version>4.12</junit.version> <spring.version>4.1.7.RELEASE</spring.version> <mybatis.version>3.2.6</mybatis.version> <org.slf4j.version>1.7.2</org.slf4j.version> <mysql.driver.version>5.1.32</mysql.driver.version> <com.fasterxml.jackson.jaxrs.version>2.4.1</com.fasterxml.jackson.jaxrs.version> <commons-fileupload.version>1.3.1</commons-fileupload.version> </properties> <dependencies> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.1.0</version> </dependency> <!-- 测试所需 --> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>${junit.version}</version> <scope>test</scope> </dependency> <!-- spring core --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>${spring.version}</version> </dependency> <!-- mybatis核心包 --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>${mybatis.version}</version> </dependency> <!-- mybatis/spring包 --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>1.2.2</version> </dependency> <!-- MySQL数据库驱动 导入 start --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>${mysql.driver.version}</version> </dependency> <!-- MySQL数据库驱动 导入 end --> <!-- 导入dbcp的jar包,数据库连接池 --> <dependency> <groupId>commons-dbcp</groupId> <artifactId>commons-dbcp</artifactId> <version>1.2.2</version> </dependency> <!-- el 标签库 --> <!-- standard.jar --> <dependency> <groupId>taglibs</groupId> <artifactId>standard</artifactId> <version>1.1.2</version> </dependency> <!-- JSTL --> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>1.1.2</version> </dependency> <!-- /el 标签库 --> <!-- 处理json --> <dependency> <groupId>com.fasterxml.jackson.jaxrs</groupId> <artifactId>jackson-jaxrs-xml-provider</artifactId> <version>${com.fasterxml.jackson.jaxrs.version}</version> </dependency> <!-- 文件上传下载 --> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>${commons-fileupload.version}</version> </dependency> <!-- slf4j 和 log4j合用的Maven配置 --> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>${org.slf4j.version}</version> </dependency> </dependencies> <build> <finalName>demo-ssm</finalName> </build> </project> </code></pre> <br /> 2.整合spring mybaties spring-mybatis.xml <pre> <code class="language-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:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd"> <!-- 引入配置文件 --> <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="location" value="classpath:jdbc.properties" /> </bean> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> <property name="driverClassName" value="${driver}" /> <property name="url" value="${url}" /> <property name="username" value="${username}" /> <property name="password" value="${password}" /> <!-- 初始化连接大小 --> <property name="initialSize" value="${initialSize}"></property> <!-- 连接池最大数量 --> <property name="maxActive" value="${maxActive}"></property> <!-- 连接池最大空闲 --> <property name="maxIdle" value="${maxIdle}"></property> <!-- 连接池最小空闲 --> <property name="minIdle" value="${minIdle}"></property> <!-- 获取连接最大等待时间 --> <property name="maxWait" value="${maxWait}"></property> </bean> <!-- ========================================针对myBatis的配置项============================== --> <!-- 配置sqlSessionFactory --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <!-- 实例化sqlSessionFactory时需要使用上述配置好的数据源以及SQL映射文件 --> <property name="dataSource" ref="dataSource" /> <!-- 自动扫描me/gacl/mapping/目录下的所有SQL映射的xml文件, 省掉Configuration.xml里的手工配置 value="classpath:com/mapper/*.xml"指的是classpath(类路径)下com.mapping包中的所有xml文件 UserMapper.xml位于com.mapping包下,这样UserMapper.xml就可以被自动扫描 --> <property name="mapperLocations" value="classpath:com/xqlee/dev/project/ssm/mapping/*.xml" /> <!-- 加载mybatis.cfg.xml文件 --> <property name="configLocation" value="classpath:mybatis.cfg.xml"></property> </bean> <!-- 配置扫描器 --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <!-- 扫描com.dao这个包以及它的子包下的所有映射接口类 --> <property name="basePackage" value="com.xqlee.dev.project.ssm.dao" /> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" /> </bean> <!-- ========================================分隔线========================================= --> <!-- (事务管理)transaction manager, use JtaTransactionManager for global tx --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource" /> </bean> </beans> </code></pre> <br /> 3.mybatis.cfg.xml <pre> <code class="language-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> </configuration></code></pre> <br /> 4.jdbc.properties <pre> <code>driver=com.mysql.jdbc.Driver url=jdbc:mysql://127.0.0.1:3306/test username=root password=root initialSize=0 maxActive=20 maxIdle=20 minIdle=1 maxWait=60000</code></pre> <br /> 5.log4j.properties <pre> <code>log4j.rootLogger=INFO,Console,File log4j.appender.Console=org.apache.log4j.ConsoleAppender log4j.appender.Console.Target=System.out log4j.appender.Console.layout = org.apache.log4j.PatternLayout log4j.appender.Console.layout.ConversionPattern=[%c] - %m%n log4j.appender.File = org.apache.log4j.RollingFileAppender log4j.appender.File.File = logs/ssm.log log4j.appender.File.MaxFileSize = 10MB log4j.appender.File.Threshold = ALL log4j.appender.File.layout = org.apache.log4j.PatternLayout log4j.appender.File.layout.ConversionPattern =[%p] [%d{yyyy-MM-dd HH\:mm\:ss}][%c]%m%n </code></pre> <br /> 6.spring-context.xml,spring容器启动配置 <pre> <code class="language-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:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:jpa="http://www.springframework.org/schema/data/jpa" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.1.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.1.xsd http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa.xsd "> <context:annotation-config /> <import resource="classpath:spring-mybatis.xml"/> <import resource="classpath:spring-mvc.xml"/> </beans></code></pre> <br /> 7.spring-mvc.xml,springMVC配置类 <pre> <code class="language-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:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.1.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd "> <!-- 自动扫描controller包下所有 --> <context:component-scan base-package="com.xqlee.dev.project.ssm" /> <!-- 注解驱动 --> <mvc:annotation-driven /> <mvc:default-servlet-handler /> <!-- 资源管理不拦截 --> <mvc:resources location="/resources/" mapping="/resources/**" /> <mvc:resources location="/upload/" mapping="/upload/**" /> <!-- 内部资源视图解析器 prefix + logicName + suffix /WEB-INF/jsps/ + index + .jsp --> <bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <!-- 前缀 --> <property name="prefix" value="/WEB-INF/pages/" /> <!-- 后缀 --> <property name="suffix" value="" /> </bean> <!-- 处理在controller中使用注解@ResponseBody标签返回JSON数据 Start --> <!-- 注意[由于我在pom.xml引入的是2.4.1版本]:所以class=org.springframework.http.converter.json.MappingJackson2HttpMessageConverter --> <!-- [如果pom.xml引入的是1.xx版本]class=org.springframework.http.converter.json.MappingJacksonHttpMessageConverter --> <bean id="mappingJackson2HttpMessageConverter" class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"> <property name="supportedMediaTypes"> <list> <value>text/html;charset=UTF-8</value> <value>text/json;charset=UTF-8</value> <value>application/json;charset=UTF-8</value> </list> </property> </bean> <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"> <property name="messageConverters"> <list> <ref bean="mappingJackson2HttpMessageConverter" /> </list> </property> </bean> <!-- JSON数据处理 End --> <!-- 上传图片/文件需要配置 --> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <property name="maxUploadSize" value="-1" /><!-- -1表示没有限制 --> <property name="maxInMemorySize" value="4096" /> </bean> </beans></code></pre> <br /> 8.User.java <pre> <code class="language-java">package com.xqlee.dev.project.ssm.pojo; public class User { private int id; private String name; private String password; private int age; /** * @return the id */ public int getId() { return id; } /** * @param id * the id to set */ public void setId(int id) { this.id = id; } /** * @return the name */ public String getName() { return name; } /** * @param name * the name to set */ public void setName(String name) { this.name = name; } /** * @return the password */ public String getPassword() { return password; } /** * @param password * the password to set */ public void setPassword(String password) { this.password = password; } /** * @return the age */ public int getAge() { return age; } /** * @param age * the age to set */ public void setAge(int age) { this.age = age; } } </code></pre> 9.UserMapper.java <pre> <code class="language-java">package com.xqlee.dev.project.ssm.dao; import java.util.List; import org.apache.ibatis.annotations.Param; import com.xqlee.dev.project.ssm.pojo.User; public interface UserMapper { User findById(@Param("id")int id); List<User> findList(@Param("name")String name); } </code></pre> 10.UserMapper.xml <pre> <code class="language-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.xqlee.dev.project.ssm.dao.UserMapper"> <resultMap id="BaseMap" type="com.xqlee.dev.project.ssm.pojo.User"> <id column="id" property="id" jdbcType="INTEGER" /><!-- 注意这里的jdbcType参考mybaties官方文档 --> <result column="name" property="name" jdbcType="VARCHAR" /> </resultMap> <!-- mapper代理开发方式,namespace的值必须是对应接口的全类名 --> <select id="findById" parameterType="int" resultType="com.xqlee.dev.project.ssm.pojo.User"> select * from t_user where id = #{id} </select> <select id="findList" resultMap="BaseMap" parameterType="java.util.Map"> select * from t_user u where 1=1 <if test="name != null"> and u.name like CONCAT('%',#{name,jdbcType=VARCHAR},'%') </if> </select> </mapper> </code></pre> 11.UserService.java <pre> <code class="language-java">package com.xqlee.dev.project.ssm.service; import java.util.List; import com.xqlee.dev.project.ssm.pojo.User; public interface UserService { User getById(int id); List<User> findList(String name); } </code></pre> 12.UserServiceImp.java <pre> <code class="language-java">package com.xqlee.dev.project.ssm.service; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.xqlee.dev.project.ssm.dao.UserMapper; import com.xqlee.dev.project.ssm.pojo.User; @Service("userService") public class UserServiceImp implements UserService { @Autowired UserMapper userMapper; @Override public User getById(int id) { return userMapper.findById(id); } @Override public List<User> findList(String name) { // TODO Auto-generated method stub return userMapper.findList(name); } } </code></pre> <br /> 13.Test.java <pre> <code class="language-java">package com.xqlee.dev.project.ssm; import java.util.List; 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 com.xqlee.dev.project.ssm.pojo.User; import com.xqlee.dev.project.ssm.service.UserService; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = { "classpath:spring-context.xml" }) public class Test { @Autowired UserService userService; @org.junit.Test public void test1() { User user = userService.getById(1); System.out.println(user.getName()); List<User> users=userService.findList(""); for(User u:users){ System.out.println("name:"+u.getName()+" id:"+u.getId()); } } } </code></pre> 14.测试表以及测试数据 <pre> <code class="language-sql">DROP TABLE IF EXISTS `t_user`; CREATE TABLE `t_user` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(40) NOT NULL, `password` varchar(255) NOT NULL, `age` int(4) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8; /*Data for the table `user_t` */ insert into `t_user`(`id`,`name`,`password`,`age`) values (1,'测试1','123456',24); insert into `t_user`(`id`,`name`,`password`,`age`) values (2,'测试2','123456',25); insert into `t_user`(`id`,`name`,`password`,`age`) values (3,'测试3','123456',26); </code></pre> 15.执行测试:<br /> <img alt="测试结果" class="img-thumbnail" src="/resources/assist/images/blog/a9af66c8-3278-4c69-a287-1019e80bbf72.jpg" style="height:515px; width:972px" /><br /> <br /> 看到上图的结果,表示spring+mybaties已经完成整合,接下来将springMVC整合进来就OK了。<br /> <br /> 16.配置web.xml,整合上面的springMVC+spring+mybaties <pre> <code class="language-xml"><web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0"> <display-name>Archetype Created Web Application</display-name> <!-- 字符集处理 --> <filter> <filter-name>CharacterEncodingFilter</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <init-param> <param-name>encoding</param-name> <param-value>utf-8</param-value> </init-param> </filter> <filter-mapping> <filter-name>CharacterEncodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <!-- spring 核心配置 --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:/spring-context.xml</param-value> </context-param> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- 配置缓存清除监听器,负责处理由 JavaBean Introspector 功能而引起的缓存泄露 --> <listener> <listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class> </listener> <!-- springMVC配置 --> <servlet> <servlet-name>springMVCSerlet</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:/spring-mvc.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>springMVCSerlet</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <!-- 添加下面容器,防止同一个服务器部署多个项目web.root冲突 --> <context-param> <param-name>webAppRootKey</param-name> <param-value>springMVC4</param-value> </context-param> <!-- session timeout --> <session-config> <!-- 分钟 --> <session-timeout>60</session-timeout> </session-config> <!-- log4j配置 --> <context-param> <param-name>log4jConfigLocation</param-name> <param-value>classpath:/log4j.properties</param-value> </context-param> <context-param> <param-name>log4jRefreshInterval</param-name> <param-value>60000</param-value> </context-param> <!--添加监听 --> <listener> <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class> </listener> <!-- /log4j配置 --> <!-- welcome page --> <welcome-file-list> <welcome-file>index.html</welcome-file> <welcome-file>index.jsp</welcome-file> </welcome-file-list> <!-- session copy --> <distributable /> </web-app></code></pre> 17.WEB-INF目录下创建pages目录,并且在里面创建一个hello.jsp<br /> hello.jsp: <pre> <code class="language-html"><%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="ISO-8859-1"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>hello</title> </head> <body> Hello ,<B>${name }</B> </body> </html></code></pre> 18.创建UserController.java <pre> <code class="language-java">package com.xqlee.dev.project.ssm.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import com.xqlee.dev.project.ssm.pojo.User; import com.xqlee.dev.project.ssm.service.UserService; @Controller public class UserController { @Autowired UserService userService; @RequestMapping("/hello/{id}.html") public String hello(@PathVariable(value="id") int id, Model model) { User user = userService.getById(id); model.addAttribute("name", user.getName()); return "hello.jsp"; } } </code></pre> <br /> 上面内容创建完成后,将项目添加到tomcat或者其他容器中,启动项目<br /> <img alt="tomcat启动日志" class="img-thumbnail" src="/resources/assist/images/blog/fab24f7c-8095-48cd-8b7c-8c6a27dd1f0c.png" style="height:684px; width:871px" /><br /> <br /> 上图是tomcat的启动日志,圈出来的是我们在UserController写的一个访问类<br /> 下面在浏览器中输入地址:<br /> <img alt="浏览器" class="img-thumbnail" src="/resources/assist/images/blog/e65e25b3-a9f8-4608-acc8-1481c12f20f4.png" style="height:323px; width:512px" /><br /> 说明:访问地址 /hello/1.html<br /> 1表示后台control中接受到的用户id的参数值。<br /> 之所以页面显示的测试1,是因为前面我们已经将测试数据导入数据库,id等于1的用户刚好名称叫测试1<br /> 至此SSM三大框架整合基础完成。
  • Spring Boot 2.0 Websocket Angular整合

    Spring Boot 2.0 Websocket Angular整合Spring Boot 2.0 Websocket Angular整合
  • spring boot 2.0 Redis整合_spring boot 2.0 集成Redis实现缓存框架(一)

    Spring Boot 2.0 Redis整合,通过spring boot 2.0整合Redis作为spring缓存框架的实现。spring boot 2.0 Redis整合_spring boot 2.0 集成Redis实现缓存框架(一)
  • spring boot 整合redis实现spring的缓存框架

    spring boot 1.5整合redis实现spring的缓存框架,spring boot,redisspring boot 整合redis实现spring的缓存框架<br /> <br /> 1.创建一个spring boot项目<br /> <img alt="项目" class="img-thumbnail" src="/resources/assist/images/blog/87917c2a16564cc08bf8e7670ec943ea.jpg" /><br /> 2.配置pom.xml文件 <pre> <code class="language-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>com.leftso</groupId> <artifactId>demo-springboot-redis</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>demo-springboot-redis</name> <description>Demo project for Spring Boot</description> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.3.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </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> </code></pre> <br /> 3.在spring boot的application配置文件中配置redis的相关信息 <pre> <code>####################Redis 配置信息 ########################## # Redis数据库分片索引(默认为0) spring.redis.database=0 # Redis服务器地址 spring.redis.host=10.1.1.134 # Redis服务器连接端口 spring.redis.port=6379 # Redis服务器连接密码(默认为空) spring.redis.password= # 连接池最大连接数(使用负值表示没有限制) spring.redis.pool.max-active=8 # 连接池最大阻塞等待时间(使用负值表示没有限制) spring.redis.pool.max-wait=-1 # 连接池中的最大空闲连接 spring.redis.pool.max-idle=8 # 连接池中的最小空闲连接 spring.redis.pool.min-idle=0 # 连接超时时间(毫秒) spring.redis.timeout=0</code></pre> <br /> 4.配置redis整合入spring的缓存框架 <pre> <code class="language-java">package com.leftso.config; import java.lang.reflect.Method; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cache.CacheManager; import org.springframework.cache.annotation.CachingConfigurerSupport; import org.springframework.cache.annotation.EnableCaching; import org.springframework.cache.interceptor.KeyGenerator; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.redis.cache.RedisCacheManager; import org.springframework.data.redis.connection.RedisConnectionFactory; import org.springframework.data.redis.core.RedisTemplate; @Configuration @EnableCaching // 继承CachingConfigurerSupport并重写方法,配合该注解实现spring缓存框架的启用 public class RedisConfig extends CachingConfigurerSupport { /** 载入通过配置文件配置的连接工场 **/ @Autowired RedisConnectionFactory redisConnectionFactory; @SuppressWarnings("rawtypes") @Autowired RedisTemplate redisTemplate; @Bean RedisTemplate<String, Object> objRedisTemplate() { RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>(); redisTemplate.setConnectionFactory(redisConnectionFactory); return redisTemplate; } /* * (non-Javadoc) * * @see org.springframework.cache.annotation.CachingConfigurerSupport# * cacheManager() */ @Bean // 必须添加此注解 @Override public CacheManager cacheManager() { RedisCacheManager redisCacheManager = new RedisCacheManager(redisTemplate); // 设置缓存过期时间 // redisCacheManager.setDefaultExpiration(60);//秒 return redisCacheManager; } /** * 重写缓存的key生成策略,可根据自身业务需要进行自己的配置生成条件 * * @see org.springframework.cache.annotation.CachingConfigurerSupport# * keyGenerator() */ @Bean // 必须项 @Override public KeyGenerator keyGenerator() { return new KeyGenerator() { @Override public Object generate(Object target, Method method, Object... params) { StringBuilder sb = new StringBuilder(); sb.append(target.getClass().getName()); sb.append(method.getName()); for (Object obj : params) { sb.append(obj.toString()); } return sb.toString(); } }; } } </code></pre> <br /> 5.创建一个测试的pojo和一个测试的controller <pre> <code class="language-java">package com.leftso.pojo; import java.io.Serializable; /** * * <pre> * [Summary] * 测试用简单类型 * [Detail] * TODO * [Author] * XQLEE * [Version] * v1.0 * 2017年5月8日上午9:58:42 * </pre> */ public class Address implements Serializable{ /** * */ private static final long serialVersionUID = 1L; private String id; private String city; private String detail; public Address() { } public Address(String id, String city, String detail) { super(); this.id = id; this.city = city; this.detail = detail; } /** * @return the id */ public String getId() { return id; } /** * @param id * the id to set */ public void setId(String id) { this.id = id; } /** * @return the city */ public String getCity() { return city; } /** * @param city * the city to set */ public void setCity(String city) { this.city = city; } /** * @return the detail */ public String getDetail() { return detail; } /** * @param detail * the detail to set */ public void setDetail(String detail) { this.detail = detail; } } </code></pre>   <pre> <code class="language-java">package com.leftso.controller; import org.springframework.cache.annotation.Cacheable; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; import com.leftso.pojo.Address; @RestController public class CacheTestCtrl { @GetMapping("/getAddr") @Cacheable(value = "address-cache") // 设置缓存的名称,也可以通过key属性指定缓存的key,keyGenerator指定key生成策略器(keyGenerator一般推荐在重写CachingConfigurerSupport类里面的方法适合全局指定) public Address getAddress() { Address addr = new Address("001", "重庆市", "渝北区"); System.out.println("==========你看见这句话表示没有缓存时候打印出来的========"); return addr; } } </code></pre> <br /> 6.启动spring boot项目,访问地址localhost:8080/getAddr<br /> 第一次访问将会在控制台中看到以下输出:<br /> <img alt="1" class="img-thumbnail" src="/resources/assist/images/blog/8273e3645def48cfb209a482857ff0ab.jpg" /><br /> <br /> 后面多次刷新都不会进入到该方法中去读取信息,而是通过缓存直接读取了缓存信息。<br /> <br /> <br /> 至此spring boot整合redis 实现基本的缓存已经完成。
  • spring boot 2.0 security 5.0 整合

    spring boot 2.0 security 5.0 整合,实现自定义表单登录。spring boot 2.0框架使用。spring boot 2.0 security 5.0 整合入门,实现自定义表单登录。 <h2>1.spring boot 2.0 security 5.0 整合需要引入的maven配置</h2> <pre> <code class="language-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>com.example</groupId> <artifactId>demo-security</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>demo-security</name> <description>Demo project for Spring Boot</description> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.0.3.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-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> </code></pre> <h2>2.spring boot 2.0 security 5.0 整合核心配置文件</h2> <pre> <code class="language-java">package com.example.demosecurity; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.builders.WebSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; @Configuration @EnableWebSecurity @EnableGlobalMethodSecurity(prePostEnabled = true) public class SecurityConfiguration extends WebSecurityConfigurerAdapter { /** * 配置忽略安全管理的路径,一般为资源文件例如css,js,IMG等 * * @param web * @throws Exception */ @Override public void configure(WebSecurity web) throws Exception { web.ignoring() .antMatchers("/webjars/**", "/resources/**"); } @Override protected void configure(HttpSecurity http) throws Exception { // super.configure(http); //注意!注意!注意!这个必须注释或者删除掉否则以下配置回受到默认您spring security规则影响 http .authorizeRequests() .antMatchers("/account/**").permitAll() .anyRequest().authenticated() .and() .formLogin() .loginPage("/account/login.html")//自定义登录页面的地址 .loginProcessingUrl("/account/login")//自定义登录表单提交地址(默认:/login) .passwordParameter("pwd")//自定义登录用密码的表单名称(默认password) .usernameParameter("username")//自定义登录用户名的表单名称(默认username) .defaultSuccessUrl("/admin")//自定义登录成功后跳转的页面 .failureForwardUrl("/account/login.html?error")//自定义登录失败跳转的页面 .and() .logout() .invalidateHttpSession(true)//登出时候清除sessionion .clearAuthentication(true)//登出时候清除认证信息 .logoutUrl("/account/logout")//登出表单的地址 .logoutSuccessUrl("/account/login.html")//登出成功后跳转页面 .and() // .csrf().disable()//配置是否启用csrf,默认启用 .cors().disable().headers().frameOptions().sameOrigin();//解决iframe无法访问 } } </code></pre> <h2>3.spring boot 2.0 security 5.0 整合配置csrf安全登录</h2> 如果在上面配置中没有禁用csrf则在登录或者登出的表单中都必须添加以下隐藏字段: <pre> <code class="language-html"><input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}" /></code></pre> <br />