搜索词>>mybaties 耗时0.0040
  • 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="/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="/assist/images/blog/5f8c20ca282f4b1c855725c473a0a5ff.png" /><br /> 执行测试代码并观察eclipse的控制台和数据库的数据查询结果:<br /> <img alt="eclipse的控制台" class="img-thumbnail" src="/assist/images/blog/552fd284c5b04a03ab408b68f7e56532.png" /><br /> <img alt="数据库查询结果" class="img-thumbnail" src="/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="/assist/images/blog/db0656c4eb684dfaad995363bf77a6ac.png" /><br /> <br /> <img alt="spring boot mybaties 整合 测试数据库查询结果" class="img-thumbnail" src="/assist/images/blog/479ffa98d4a64ef888e6cf6654e0f956.png" /><br /> <br /> 这次的操作姿势似乎对了。在报错的情况下数据并没有插入数据库。我们仔细观察spring 控制台输出的日志可以发现事物已经在spring的控制下回滚了。<br /> <img alt="spring boot mybaties 整合 测试异常回滚eclipse控制台日志输出结果" class="img-thumbnail" src="/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="/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>
  • mybaties 处理集合(List)参数_mybaties 处理 IN条件

    某些情况下,我们使用mybaties时需要使用IN(虽然IN数据多了效率不高,但是少量还是可以用得)条件查询,这时候我们就需要传递参数了,下面是mybaties处理IN条件得参数使用方法首先Mapper接口需要传递一个集合数据过来,集合数据某些情况下,我们使用mybaties时需要使用IN(虽然IN数据多了效率不高,但是少量还是可以用得)条件查询,这时候我们就需要传递参数了,下面是mybaties处理IN条件得参数使用方法首先Mapper接口需要传递一个集合数据过来,集合数据可以是对象也可以是简单类型,下面以简单类型为例:$title(TestMapper.java) List<User> getListIdIn(@Param("ids")List<String> ids);接下来是mapper xml文件$title(TestMapper.xml) ...省略其他代码.... <if test="ids!=null and ids.size()>0"> and id in <foreach collection="ids" item="id" index="index" open="(" close=")" separator=","> #{id} </foreach> </if> ...省略其他代码...
  • mybaties mapper 继承机制解决改表改mapper的苦恼

           本文主要讲解在使用mybaties中通过mybaties generator生成基本操作代码,然后通过 mybaties mapper 继承机制来解决某些情况下经常改表导致改mapper文件的苦恼       本文主要讲解在使用mybaties中通过mybaties generator生成基本操作代码,然后通过 mybaties mapper 继承机制来解决某些情况下经常改表导致改mapper文件的苦恼。好了废话少说上代码了首先是 mapper java文件的继承$title(ArticleMapper.java) public interface ArticleMapper { int deleteByPrimaryKey(Integer id); int insert(Article record); int insertSelective(Article record); Article selectByPrimaryKey(Integer id); int updateByPrimaryKeySelective(Article record); int updateByPrimaryKey(Article record); }以上mapper文件为mybaties generator生成的代码。$title(ArticleExtMapper.java) public interface ArticleExtMapper extends ArticleMapper { Article getLast(@Param("id") Integer id, @Param("type") Integer type); Article getNext(@Param("id") Integer id, @Param("type") Integer type); List<Article> getList(@Param("title") String title, @Param("category") String category, @Param("type") Integer type); } 以上为业务使用中扩展的一些应用查询方法下面上mapper xml文件的使用$title(ArticleMapper.xml) <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="net.ifok.ocms.business.mapper.ArticleMapper"> <resultMap id="BaseResultMap" type="net.ifok.ocms.business.model.Article"> <id column="id" jdbcType="INTEGER" property="id" /> <result column="title" jdbcType="VARCHAR" property="title" /> <result column="image" jdbcType="VARCHAR" property="image" /> <result column="url" jdbcType="VARCHAR" property="url" /> <result column="content" jdbcType="VARCHAR" property="content" /> <result column="content_text" jdbcType="VARCHAR" property="contentText" /> <result column="category" jdbcType="VARCHAR" property="category" /> <result column="type" jdbcType="INTEGER" property="type" /> <result column="create_time" jdbcType="TIMESTAMP" property="createTime" /> <result column="update_time" jdbcType="TIMESTAMP" property="updateTime" /> <result column="keywords" jdbcType="VARCHAR" property="keywords" /> <result column="description" jdbcType="VARCHAR" property="description" /> <result column="customer" jdbcType="VARCHAR" property="customer" /> </resultMap> <sql id="Base_Column_List"> id, title, image, url, content, content_text, category, type, create_time, update_time, keywords, description, customer </sql> <select id="selectByPrimaryKey" parameterType="java.lang.Integer" resultMap="BaseResultMap"> select <include refid="Base_Column_List" /> from article where id = #{id,jdbcType=INTEGER} </select> <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer"> delete from article where id = #{id,jdbcType=INTEGER} </delete> <insert id="insert" parameterType="net.ifok.ocms.business.model.Article"> insert into article (id, title, image, url, content, content_text, category, type, create_time, update_time, keywords, description, customer) values (#{id,jdbcType=INTEGER}, #{title,jdbcType=VARCHAR}, #{image,jdbcType=VARCHAR}, #{url,jdbcType=VARCHAR}, #{content,jdbcType=VARCHAR}, #{contentText,jdbcType=VARCHAR}, #{category,jdbcType=VARCHAR}, #{type,jdbcType=INTEGER}, #{createTime,jdbcType=TIMESTAMP}, #{updateTime,jdbcType=TIMESTAMP}, #{keywords,jdbcType=VARCHAR}, #{description,jdbcType=VARCHAR}, #{customer,jdbcType=VARCHAR}) </insert> <insert id="insertSelective" parameterType="net.ifok.ocms.business.model.Article"> insert into article <trim prefix="(" suffix=")" suffixOverrides=","> <if test="id != null"> id, </if> <if test="title != null"> title, </if> <if test="image != null"> image, </if> <if test="url != null"> url, </if> <if test="content != null"> content, </if> <if test="contentText != null"> content_text, </if> <if test="category != null"> category, </if> <if test="type != null"> type, </if> <if test="createTime != null"> create_time, </if> <if test="updateTime != null"> update_time, </if> <if test="keywords != null"> keywords, </if> <if test="description != null"> description, </if> <if test="customer != null"> customer, </if> </trim> <trim prefix="values (" suffix=")" suffixOverrides=","> <if test="id != null"> #{id,jdbcType=INTEGER}, </if> <if test="title != null"> #{title,jdbcType=VARCHAR}, </if> <if test="image != null"> #{image,jdbcType=VARCHAR}, </if> <if test="url != null"> #{url,jdbcType=VARCHAR}, </if> <if test="content != null"> #{content,jdbcType=VARCHAR}, </if> <if test="contentText != null"> #{contentText,jdbcType=VARCHAR}, </if> <if test="category != null"> #{category,jdbcType=VARCHAR}, </if> <if test="type != null"> #{type,jdbcType=INTEGER}, </if> <if test="createTime != null"> #{createTime,jdbcType=TIMESTAMP}, </if> <if test="updateTime != null"> #{updateTime,jdbcType=TIMESTAMP}, </if> <if test="keywords != null"> #{keywords,jdbcType=VARCHAR}, </if> <if test="description != null"> #{description,jdbcType=VARCHAR}, </if> <if test="customer != null"> #{customer,jdbcType=VARCHAR}, </if> </trim> </insert> <update id="updateByPrimaryKeySelective" parameterType="net.ifok.ocms.business.model.Article"> update article <set> <if test="title != null"> title = #{title,jdbcType=VARCHAR}, </if> <if test="image != null"> image = #{image,jdbcType=VARCHAR}, </if> <if test="url != null"> url = #{url,jdbcType=VARCHAR}, </if> <if test="content != null"> content = #{content,jdbcType=VARCHAR}, </if> <if test="contentText != null"> content_text = #{contentText,jdbcType=VARCHAR}, </if> <if test="category != null"> category = #{category,jdbcType=VARCHAR}, </if> <if test="type != null"> type = #{type,jdbcType=INTEGER}, </if> <if test="createTime != null"> create_time = #{createTime,jdbcType=TIMESTAMP}, </if> <if test="updateTime != null"> update_time = #{updateTime,jdbcType=TIMESTAMP}, </if> <if test="keywords != null"> keywords = #{keywords,jdbcType=VARCHAR}, </if> <if test="description != null"> description = #{description,jdbcType=VARCHAR}, </if> <if test="customer != null"> customer = #{customer,jdbcType=VARCHAR}, </if> </set> where id = #{id,jdbcType=INTEGER} </update> <update id="updateByPrimaryKey" parameterType="net.ifok.ocms.business.model.Article"> update article set title = #{title,jdbcType=VARCHAR}, image = #{image,jdbcType=VARCHAR}, url = #{url,jdbcType=VARCHAR}, content = #{content,jdbcType=VARCHAR}, content_text = #{contentText,jdbcType=VARCHAR}, category = #{category,jdbcType=VARCHAR}, type = #{type,jdbcType=INTEGER}, create_time = #{createTime,jdbcType=TIMESTAMP}, update_time = #{updateTime,jdbcType=TIMESTAMP}, keywords = #{keywords,jdbcType=VARCHAR}, description = #{description,jdbcType=VARCHAR}, customer = #{customer,jdbcType=VARCHAR} where id = #{id,jdbcType=INTEGER} </update> </mapper> 以上为mybaties generator生成的代码。 $title(ArticleExtMapper.xml) <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="net.ifok.ocms.business.mapper.ext.ArticleExtMapper"> <resultMap id="BaseResultMap" type="net.ifok.ocms.business.model.Article" extends="net.ifok.ocms.business.mapper.ArticleMapper.BaseResultMap"> </resultMap> <select id="getLast" resultMap="BaseResultMap"> select * FROM article where type=${type} and id <![CDATA[ < ]]> #{id} order by id desc limit 1 </select> <select id="getNext" resultMap="BaseResultMap"> select * FROM article where type=#{type} and id <![CDATA[ > ]]>#{id} order by id asc limit 1 </select> <select id="getList" resultMap="BaseResultMap"> SELECT * from article where 1=1 and type=#{type} <if test="title!=null"> and title like CONCAT(CONCAT('%', #{title}), '%') </if> <if test="category !=null and category !=''"> and category=#{category} </if> order by create_time desc </select> </mapper> 以上为扩展查询事项说明:ArticleMapper中有,ArticleExtMapper.xml中没有,ArticleExtMapper沿用ArticleMapper中的定义ArticleMapper中有,ArticleExtMapper.xml中也有,ArticleExtMapper使用ArticleExtMapper.xml中的定义ArticleMapper中没有,ArticleExtMapper.xml中有,ArticleExtMapper使用ArticleExtMapper.xml中的定义  ResultMap覆盖Mapper.xml继承机制只针对statement有效,对于sql、resultMap是无效的。如果要在ArticleExtMapper.xml中覆盖这些,必须要先覆盖ParentMapper.xml中的statement,然后让这些statement使用新的sql、resultMap等。总结通过上面的将扩展的部分分开来写,后续改表,生成部分的代码直接覆盖即可,不担心扩展的不见了,二使用的时候直接使用扩展的mapper即可,扩展的mapper包含所有的方法。over ,Enjoy​​​​​​​
  • mybaties like参数写法

    mybaties like参数写法 and a.link like CONCAT(CONCAT('%', #{params.link}), '%')mybaties like参数写法 and a.link like CONCAT(CONCAT('%', #{params.link}), '%')
  • 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="/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>