搜索词>>mybaties 耗时0.0020
  • 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 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 />  
  • mybaties generator 表名/字段名下划线转驼峰

    mybaties generator 表名/字段名下划线转驼峰,Spring Boot 2.0 整合 mybaties generator 表名/字段名下划线转驼峰 idea上的配置一、前言mybaties generator在使用mybaties框架开发的时候会给我们省下一大笔写基础代码的时间。对我们程序员来说真是太好啦。(废话结束)二、mybaties generator 驼峰配置主要是改mybaties generator的配置文件。可参考之前发布的idea Mybatis generator插件的配置和使用 查看默认配置修改表格部分如下:<table tableName="user_info" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false"> <property name="useActualColumnNames" value="false" /> <!--true:MyBatis Generator会使用数据库中实际的字段名字作为生成的实体类的属性名。   false:这是默认值。如果设置为false,则MyBatis Generator会将数据库中实际的字段名字转换为Camel Case风格作为生成的实体类的属性名。--> </table>修改配置完成后就可以实现表明字段名都下划线转驼峰啦
  • 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>
  • 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>
  • idea Mybatis generator插件的配置和使用

    idea Mybatis generator插件的配置和使用,在eclipse中,我们可以在eclipse的插件市场安装一个Mybatis generator的插件。然后对Mybatis generator插件的配置文件进行右键run就好啦。IDea中目前还没发现这么快捷的插件。但是也可以使用maven的方式来实现。    idea Mybatis generator插件的配置和使用,在eclipse中,我们可以在eclipse的插件市场安装一个Mybatis generator的插件。然后对Mybatis generator插件的配置文件进行右键run就好啦。IDea中目前还没发现这么快捷的插件。但是也可以使用maven的方式来实现。 <h2>步骤一:添加Mybatis generator依赖</h2> <pre> <code class="language-xml"><plugin> <!--Mybatis-generator插件,用于自动生成Mapper和POJO--> <groupId>org.mybatis.generator</groupId> <artifactId>mybatis-generator-maven-plugin</artifactId> <version>1.3.6</version> <configuration> <!--配置文件的位置--> <configurationFile>src/main/resources/mybatisGeneratorConfigl.xml</configurationFile> <verbose>true</verbose> <overwrite>true</overwrite> </configuration> <executions> <execution> <id>Generate MyBatis Artifacts</id> <goals> <goal>generate</goal> </goals> <execution> <id>life</id> <phase>deploy</phase> </execution><!--避免执行package执行该插件--> </execution> </executions> <dependencies> <dependency> <groupId>org.mybatis.generator</groupId> <artifactId>mybatis-generator-core</artifactId> <version>1.3.6</version> </dependency> </dependencies> </plugin> </code></pre> <blockquote> <p>注意添加的节点是plugin</p> </blockquote> <br /> <br />   <h2>步骤二:编写Mybatis generator配置文件</h2> <pre> <code class="language-xml"><?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE generatorConfiguration PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN" "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd"> <generatorConfiguration> <classPathEntry location="D:/maven_res/mysql/mysql-connector-java/5.1.29/mysql-connector-java-5.1.29.jar" /> <context id="mysqlTables" targetRuntime="MyBatis3"> <plugin type="org.mybatis.generator.plugins.SerializablePlugin" /> <commentGenerator> <property name="suppressDate" value="true" /> <property name="suppressAllComments" value="true" /> </commentGenerator> <!-- 数据库链接URL、用户名、密码 --> <jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://127.0.0.1:3306/sdf" userId="root" password="root"> </jdbcConnection> <javaTypeResolver> <property name="forceBigDecimals" value="false" /> </javaTypeResolver> <javaModelGenerator targetPackage="com.sdf.enterprise.business.model" targetProject="d:/workplace/idea/sdf-service/src/main/java"> <property name="enableSubPackages" value="true" /> <!-- 从数据库返回的值被清理前后的空格 --> <property name="trimStrings" value="true" /> </javaModelGenerator> <!--对应的mapper.xml文件 --> <sqlMapGenerator targetPackage="mapper" targetProject="d:/workplace/idea/sdf-service/src/main/resources/"> <property name="enableSubPackages" value="true" /> </sqlMapGenerator> <!-- 对应的Mapper接口类文件 --> <javaClientGenerator type="XMLMAPPER" targetPackage="com.sdf.enterprise.business.mapper" targetProject="d:/workplace/idea/sdf-service/src/main/java"> <property name="enableSubPackages" value="true" /> </javaClientGenerator> <!-- 列出要生成代码的所有表,这里配置的是生成Example文件 --> <table tableName="patent"/> </context> </generatorConfiguration> </code></pre> <blockquote> <p>注意:在idea中配置文件需要填写项目的绝对路径。不像eclipse插件可以配置项目相对路径。</p> </blockquote> <h2>步骤三:Mybatis generator插件使用</h2> <img alt="Mybatis generator插件使用" class="img-thumbnail" src="/resources/assist/images/blog/9514b21590a44f35aff504706feaf246.png" /><br /> 如上图。点击Mybatis generator插件即可运行生成代码。<br /> <br /> <br /> <br /> <br /> <br /> <br /> <br /> <br /> <br /> <br /> <br /> <br />  
  • 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>
  • mybatis的缓存机制(一级缓存二级缓存和刷新缓存)

    mybatis事物访问数据库的一级缓存和二级缓存和刷新缓存<p>背景:今天在公司的一个项目中查询一个数据,一个query方法,在同一个事务中查询了两次,但是第二次查询的结果始终和第一次完全一致,刚开始以为是查询方法写作了,但是后面一想只有参数不一致,没有什么异同,断点模式追踪发现是mybatis自带的缓存机制导致,顺便记录下。</p> <h2><strong>一、什么是查询缓存</strong></h2> <p>mybatis提供查询缓存,用户减轻数据压力,提供数据库性能,并且提供一级缓存和二级缓存。如下图</p> <p><img alt="" class="img-thumbnail" src="/resources/assist/images/blog/8d7949c5ea3f462f971b5fca1a53a974.png" /><br /> 1、一级缓存是sqlsession级别的缓存,在操作数据库时需要构造sqlsession对象,在对象中有一个(内存区域)数据结构(hashmap)用于存储缓存数据。不同的sqlsession之间的缓存数据区域(hashmap)是互相不影响的。<br /> <br />     一级缓存的作用域是同一个sqlsession,在同一个sqlsession中两次执行相同的sql语句,第一次执行完毕会将数据库中查询的数据写入搭配缓存(内存),第二次会从缓存中获取数据,将不在从数据库查询,从而提高查询效率。当一个sqlsession结束后该sqlsession中的一级缓存也就不存在,mybatis默认开启一级缓存。<br /> <br /> 2、二级缓存是mapper级别的缓存,多个sqlsession去操作同一个mapper的sql语句,多个sqlsession区操作数据得到数据会存在二级缓存区域,多个sqlsession可以共用二级缓存,二级缓存是跨sqlsession的。<br /> <br />     二级缓存是多个sqlsession共享的,起作用域是mapper的同以一个namespace,不同的sqlsession两次执行相同的namespace下的sql语句且向sql传递的参数也相同即最终执行相同的sql语句,第一次执行完毕会将数据写到缓存(内存),第二次会从缓存中获取数据将不再从数据库查询,从而提高效率,mybatis默认没有开启二级缓存需要setting全部参数中配置开启二级缓存。<br /> <br /> 如果缓存中有数据就将不会从数据库获取,提高系统性能。</p> <h2> <strong>二、一级缓存</strong><br /> <br /> <img alt="" class="img-thumbnail" src="/resources/assist/images/blog/2b63d8a91f07490cb0e734f90dfe9196.png" /></h2> <p>    第一次发起查询用户id为1的用户信息,先去找缓存中是否有id为1的用户信息,如果没有,从数据库查询用户信息。得到用户信息,将用户信息存储到一级缓存中。如果<strong>sqlSession去执行commit操作(执行插入、更新、删除),清空SqlSession中的一级缓</strong>存,这样做的目的为了让缓存中存储的是最新的信息,避免脏读。第二次发起查询用户id为1的用户信息,先去找缓存中是否有id为1的用户信息,缓存中有,直接从缓存中获取用户信息。<br />     一级缓存的应用:开发中,是将mybatis和spring进行整合开发,事务控制在service中,一个service方法中包括很多mapper方法调用,一个service中相同的调用mapper中相同方法,后面调取会直接从一级缓存中取数据。方法结束,sqlSession关闭 sqlsession关闭后就销毁数据结构,清空缓存Service结束sqlsession关闭。如果是执行两次service调用查询相同的用户信息,不走一级缓存,因为Service方法结束,sqlSession就关闭,一级缓存就清空。</p> <h2><strong>三、二级缓存</strong></h2> <p>  <img alt="" class="img-thumbnail" src="/resources/assist/images/blog/088bad7be6874e50b281bcaac6f36616.png" /></p> <p>    mybatis二级缓存需要配置开启,二级缓存与一级缓存区别,二级缓存的范围更大,多个sqlSession可以共享一个UserMapper的二级缓存区域。数据类型仍然为HashMap。UserMapper有一个二级缓存区域(按namespace分,如果namespace相同则使用同一个相同的二级缓存区),其它mapper也有自己的二级缓存区域(按namespace分)。每一个namespace的mapper都有一个二缓存区域,两个mapper的namespace如果相同,这两个mapper执行sql查询到数据将存在相同的二级缓存区域中。<br />     开启二级缓存:只需要在mapper.xml文件中添加</p> <pre> <code class="language-xml"><cache/> </code></pre> 如下: <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.cqax.business.dao.PictureMapper"> <!-- 开启mybatis二级缓存 --> <cache/> <resultMap id="BaseResultMap" type="com.cqax.business.model.Picture"> <id column="id" jdbcType="BIGINT" property="id" /> <result column="created" jdbcType="TIMESTAMP" property="created" /> <result column="type" jdbcType="INTEGER" property="type" /> <result column="updated" jdbcType="TIMESTAMP" property="updated" /> <result column="operator_id" jdbcType="BIGINT" property="operatorId" /> <result column="picture_id" jdbcType="BIGINT" property="pictureId" /> <result column="student_id" jdbcType="BIGINT" property="studentId" /> <result column="sign_id" jdbcType="BIGINT" property="signId" /> <result column="signsecretkey" jdbcType="VARCHAR" property="signsecretkey" /> <result column="transferstatus" jdbcType="INTEGER" property="transferstatus" /> <result column="deviceid" jdbcType="VARCHAR" property="deviceid" /> <result column="fingerstatus" jdbcType="TINYINT" property="fingerstatus" /> <result column="sendtimer" jdbcType="INTEGER" property="sendtimer" /> </resultMap></code></pre> <h2><strong>四、mybatis刷新缓存(清空缓存)</strong></h2> <p>在mapper的同一个namespace中,如果有其它insert、update、delete操作数据后需要刷新缓存,如果不执行刷新缓存会出现脏读。 设置statement配置中的flushCache='true' 属性,默认情况下为true即刷新缓存,如果改成false则不会刷新。使用缓存时如果手动修改数据库表中的查询数据会出现脏读。<br /> 比如:</p> <pre> <code class="language-xml"><insertid='insertUser' parameterType='cn.itcast.mybatis.po.User' flushCache='true'></code></pre> 一般下执行完commit操作都需要刷新缓存,flushCache=true表示刷新缓存默认情况下为true,我们不用去设置它,这样可以避免数据库脏读。 <h2><strong>五、Mybatis Cache参数</strong></h2> <p>flushInterval(刷新间隔)可以被设置为任意的正整数,而且它们代表一个合理的毫秒形式的时间段。默认情况是不设置,也就是没有刷新间隔,缓存仅仅调用语句时刷新。size(引用数目)可以被设置为任意正整数,要记住你缓存的对象数目和你运行环境的可用内存资源数目。默认值是1024。readOnly(只读)属性可以被设置为true或false。只读的缓存会给所有调用者返回缓存对象的相同实例。因此这些对象不能被修改。这提供了很重要的性能优势。可读写的缓存会返回缓存对象的拷贝(通过序列化)。这会慢一些,但是安全,因此默认是false。<br /> 例如:</p> <pre> <code class="language-xml"><cache eviction='FIFO' flushInterval='60000' size='512' readOnly='true'/></code></pre> <p>这个更高级的配置创建了一个 FIFO 缓存,并每隔 60 秒刷新,存数结果对象或列表的 512 个引用,而且返回的对象被认为是只读的,因此在不同线程中的调用者之间修改它们会导致冲突。可用的收回策略有, 默认的是 LRU:</p> <p>1.LRU – 最近最少使用的:移除最长时间不被使用的对象。</p> <p>2.FIFO – 先进先出:按对象进入缓存的顺序来移除它们。</p> <p>3.SOFT – 软引用:移除基于垃圾回收器状态和软引用规则的对象。</p> <p>4.WEAK – 弱引用:更积极地移除基于垃圾收集器状态和弱引用规则的对象。</p> <h2><strong>六、顺带说下mybatis的xml文件sql中每个字段配置属性</strong></h2> <table border="1" cellspacing="0" class="table table-bordered table-hover" style="border-collapse:collapse; border-spacing:0px; border:1px solid #dddddd; box-sizing:border-box; color:#333333; font-family:"Helvetica Neue",Helvetica,Arial,sans-serif; font-size:14px; margin-bottom:20px; max-width:100%; width:1025px"> <tbody> <tr> <td>id</td> <td style="background-color:#f9f9f9; vertical-align:top">在命名空间中唯一的标识符,可以被用来引用这条语句。</td> </tr> <tr> <td>parameterType</td> <td style="vertical-align:top">将会传入这条语句的参数类的完全限定名或别名。这个属性是可选的,因为 MyBatis 可以通过 TypeHandler 推断出具体传入语句的参数,默认值为 unset。</td> </tr> <tr> <td>resultType</td> <td style="background-color:#f9f9f9; vertical-align:top">从这条语句中返回的期望类型的类的完全限定名或别名。注意如果是集合情形,那应该是集合可以包含的类型,而不能是集合本身。使用 resultType 或 resultMap,但不能同时使用。</td> </tr> <tr> <td>resultMap</td> <td style="background-color:#f9f9f9; vertical-align:top">外部 resultMap 的命名引用。结果集的映射是 MyBatis 最强大的特性,对其有一个很好的理解的话,许多复杂映射的情形都能迎刃而解。使用 resultMap 或 resultType,但不能同时使用。</td> </tr> <tr> <td>flushCache</td> <td style="background-color:#f9f9f9; vertical-align:top">将其设置为 true,任何时候只要语句被调用,都会导致本地缓存和二级缓存都会被清空,默认值:false。</td> </tr> <tr> <td>useCache</td> <td style="background-color:#f9f9f9; vertical-align:top">将其设置为 true,将会导致本条语句的结果被二级缓存,默认值:对 select 元素为 true。</td> </tr> <tr> <td>timeout</td> <td style="background-color:#f9f9f9; vertical-align:top">这个设置是在抛出异常之前,驱动程序等待数据库返回请求结果的秒数。默认值为 unset(依赖驱动)。</td> </tr> <tr> <td>fetchSize</td> <td style="background-color:#f9f9f9; vertical-align:top">这是尝试影响驱动程序每次批量返回的结果行数和这个设置值相等。默认值为 unset(依赖驱动)。</td> </tr> <tr> <td>statementType</td> <td style="background-color:#f9f9f9; vertical-align:top">STATEMENT,PREPARED 或 CALLABLE 的一个。这会让 MyBatis 分别使用 Statement,PreparedStatement 或 CallableStatement,默认值:PREPARED。</td> </tr> <tr> <td>resultSetType</td> <td style="background-color:#f9f9f9; vertical-align:top">FORWARD_ONLY,SCROLL_SENSITIVE 或 SCROLL_INSENSITIVE 中的一个,默认值为 unset (依赖驱动)。</td> </tr> <tr> <td>databaseId</td> <td style="background-color:#f9f9f9; vertical-align:top">如果配置了 databaseIdProvider,MyBatis 会加载所有的不带 databaseId 或匹配当前 databaseId 的语句;如果带或者不带的语句都有,则不带的会被忽略。</td> </tr> <tr> <td>resultOrdered</td> <td>这个设置仅针对嵌套结果 select 语句适用:如果为 true,就是假设包含了嵌套结果集或是分组了,这样的话当返回一个主结果行的时候,就不会发生有对前面结果集的引用的情况。这就使得在获取嵌套的结果集的时候不至于导致内存不够用。默认值:false。</td> </tr> <tr> <td>resultSets</td> <td style="background-color:#f9f9f9; vertical-align:top">这个设置仅对多结果集的情况适用,它将列出语句执行后返回的结果集并每个结果集给一个名称,名称是逗号分隔的。</td> </tr> </tbody> </table> <h3>下面特别说明下之前遇到的问题</h3> 1.flushCache<br /> 当为select语句时:flushCache默认为false,表示任何时候语句被调用,都不会去清空本地缓存和二级缓存。<br /> 当为insert、update、delete语句时:flushCache默认为true,表示任何时候语句被调用,都会导致本地缓存和二级缓存被清空。<br /> <br /> 2.useCache<br /> 当为select语句时:useCache默认为true,表示会将本条语句的结果进行二级缓存。<br /> 当为insert、update、delete语句时:useCache属性在该情况下没有。<br /> <br /> 当为select语句的时候,如果没有去配置flushCache、useCache,那么默认是启用缓存的,所以,如果有必要,那么就需要人工修改配置,修改结果类似下面: <pre> <code class="language-xml"><select id="save" parameterType="XX" flushCache="true" useCache="false">     …… </select></code></pre> update 的时候如果 flushCache="false",则当你更新后,查询的数据数据还是老的数据。<br /> <br /> <br />  
  • @Select注解中动态sql处理mybaties

    在Java编程中,ORM框架mybaties处理@Select注解中的动态sql处理方法在Java编程中,ORM框架mybaties处理@Select注解中的动态sql处理方法<br /> <br /> 代码如下 <pre> <code class="language-java">public interface UserMapper { @Select("<script>select * from user u where u.id in <foreach collection=\"ids\" item=\"item\" index=\"index\" open=\"(\" close=\")\" separator=\",\"> #{item}</foreach> </script>") @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> list(@Param("ids")Long [] ids); }</code></pre> <br /> <strong>简单的说就是讲以前mapper.XML中的sql写法搬到Java代码中.用<SCRIPT></SCRIPT>包裹起来</strong>
  • 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三大框架整合基础完成。