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

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

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

    spring boot项目中使用logback日志,USING LOGBACK WITH SPRING BOOT ,Logback让一个优秀的企业应用程序的日志框架——它是快速,简单但强大的配置选项,有一个小的内存占用。我在介绍性的文章,介绍logback.Logback简介:一个企业日志框架。在Logback一系列的文章中,我讨论了如何使用XML配置Logback和Groovy。可选用的Logback配置:使用XML和Logback配置:使用Groovy.<h2>  引言</h2> <p>    Logback让一个优秀的企业应用程序的日志框架——它是快速,简单但强大的配置选项,有一个小的内存占用。我在介绍性的文章,介绍logback.Logback简介:一个企业日志框架。在Logback一系列的文章中,我讨论了如何使用XML配置Logback和Groovy。可选用的Logback配置:使用XML和Logback配置:使用Groovy.</p> <p>    在这篇文章中,我将讨论如何使用Logback spring boot 。虽然有许多Java日志记录选项,默认的 spring boot 选择使用Logback记录器。像许多东西在春天的引导,Logback默认配置合理的默认值。开箱即用的,spring boot使得Logback易于使用。</p> <h2>详细介绍</h2> <h4> </h4> <h3>创建日志记录器</h3> <p>    在以前的文章,我写过一篇关于如何用spring boot创建一个web应用。这里将会为这个web应用配置logback日志。这个应用包含  IndexController我们将添加日志记录代码。IndexController的代码是这样的。</p> <pre> <code class="language-java">package guru.springframework.controllers;     import guru.springframework.helpers.SpringLoggingHelper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping;   @Controller public class IndexController {     private final Logger logger = LoggerFactory.getLogger(this.getClass());     @RequestMapping("/")     String index(){         logger.debug("This is a debug message");         logger.info("This is an info message");         logger.warn("This is a warn message");         logger.error("This is an error message");         new SpringLoggingHelper().helpMethod();         return "index";     } }</code></pre> <p>让我们添加一个 SpringLoggingHelper类与应用程序日志代码。虽然这类不做任何事除了释放日志语句,它将帮助我们理解配置日志记录在不同的包中。这是SpringLoggingHelper 的代码:</p> <pre> <code class="language-java">package guru.springframework.helpers;     import org.slf4j.Logger; import org.slf4j.LoggerFactory;   public class SpringLoggingHelper {     private final Logger logger = LoggerFactory.getLogger(this.getClass());     public void helpMethod(){         logger.debug("This is a debug message");         logger.info("This is an info message");         logger.warn("This is a warn message");         logger.error("This is an error message");       } }</code></pre> <p>在上面的类中,我们写日志代码对SLF4J API。SLF4J是常用的外墙日志框架,如Java Util日志,Log4J 2和Logback。通过编写SLF4J,我们的代码仍然和Logback解耦,从而提供插件不同的日志框架的灵活性,以后如果需要。</p> <p>如果你想知道关于SLF4J和Logback依赖性,你不需要指定任何。spring boot包含它们。假设您正在使用Maven或Gradle管理你春天启动项目,必要的依赖关系是 spring boot 下的依赖关系的一部分。</p> <p>运行 SpringBootWebApplication主类。当应用程序启动时,从你的浏览器的URL访问它,<strong>http://localhost:8080</strong></p> <p>IntelliJ控制台的日志输出。</p> <p><img alt="在弹簧启动时使用默认配置记录输出" class="img-thumbnail" src="https://i2.wp.com/springframework.guru/wp-content/uploads/2016/04/logging_output_with_springboot-1024x266.png?resize=863%2C224&ssl=1" /></p> <p>我们还没有写任何Logback配置。输出的 IndexController和 SpringLoggingHelper从logback根记录器类。注意,调试消息没有得到记录。Logback默认情况下将日志消息调试水平。然而, spring boot 团队给我们提供了一个默认的配置在theSpring Logback启动默认Logback配置文件, 基地.xml。此外,Spring提供了提供两个预配置的输出源通过引导 控制台- - - - - -appender.xml和 文件- - - - - -appender.xml文件。的 基地.xml文件referencesboth。</p> <p>这是base.xml的代码,文件从spring-boot github获取。</p> <pre> <code class="language-xml"><?xml version="1.0" encoding="UTF-8"?>   <!-- Base logback configuration provided for compatibility with Spring Boot 1.1 -->   <included> <include resource="org/springframework/boot/logging/logback/defaults.xml" /> <property name="LOG_FILE" value="${LOG_FILE:-${LOG_PATH:-${LOG_TEMP:-${java.io.tmpdir:-/tmp}}}/spring.log}"/> <include resource="org/springframework/boot/logging/logback/console-appender.xml" /> <include resource="org/springframework/boot/logging/logback/file-appender.xml" /> <root level="INFO"> <appender-ref ref="CONSOLE" /> <appender-ref ref="FILE" /> </root> </included></code></pre> <p>在这里您可以看到,通过将根记录器设置为INFO,Spring Boot已经覆盖了Logback的默认日志记录级别 ,这是上面示例中没有看到调试消息的原因。我们将在下一节中看到,在Spring Boot中更改日志级别非常简单。</p> <br /> 查看我的免费简介春季课程 <h4>通过Spring Boot的application.properties文件进行配置</h4> <p>在Spring Boot应用程序中,您可以外部化配置以在不同的环境中使用相同的应用程序代码。application.properties。属性文件可能是最受欢迎的几种不同的方法来外部化Spring Boot配置属性。在Spring Boot Web应用程序的默认结构中,可以找到application.properties。资源文件夹下的 属性文件。在application.properties中。属性文件,您可以定义Spring Boot的日志级别,应用程序记录器,Hibernate,Thymeleaf等。您还可以定义一个日志文件以将日志消息写入到控制台之外。</p> <p>下面是一个示例 应用。属性文件与日志配置。</p> <pre> <code>logging.level.org.springframework.web=INFO logging.level.guru.springframework.controllers=DEBUG logging.level.org.hibernate=ERROR logging.file=logs/spring-boot-logging.log</code></pre> <p><br /> 当您现在运行主类并访问应用程序时,将来自IndexController和 SpringLoggingHelper的日志消息 记录到控制台和logs / spring - boot - logging 。日志文件。<strong>注意</strong>:还有一个 日志记录。path属性来指定日志记录文件的路径。如果你使用它,Spring Boot会创建一个spring。日志文件在指定的路径。但是,您不能同时指定 日志记录。文件和 日志记录。路径属性在一起。如果完成,Spring Boot将忽略两者。</p> <p><img alt="使用application.properties启动Spring启动日志输出" class="img-thumbnail" src="https://i2.wp.com/springframework.guru/wp-content/uploads/2016/04/logging_output_with_application_properties-1024x486.png?resize=863%2C410&ssl=1" /></p> <p>在输出中,请注意IndexController的调试和更高级别的消息 已记录到控制台和文件中。这是因为在application.properties中。属性文件中,我们指定 DEBUG作为日志级 大师。springframework的。控制器包, IndexController是其中的一部分。由于我们没有明确配置 SpringLoggingHelper类,所以默认配置为 base 。使用了xml文件。因此,只有 记录了SpringLoggingHelper的INFO和更高级别的消息 。</p> <p>当您需要获取特定类或包的更详细的日志消息时,可以看到这是多么简单。</p> <h4>通过外部文件进行回溯配置</h4> <p>通过application.properties回溯配置。属性文件将足够用于许多Spring Boot应用程序。然而,大型企业应用程序可能会有更复杂的日志记录要求。如前所述,Logback通过<a href="https://springframework.guru/logback-configuration-using-xml/" rel="external nofollow" target="_blank">XML</a>和Groovy配置文件支持高级日志记录配置。</p> <p>在Spring Boot应用程序中,您可以将Logback XML配置文件指定为 logback 。xml或 logback - spring 。xml在项目类路径中。然而,Spring Boot团队建议使用<strong>-spring</strong>变体进行日志记录配置,   logback - spring 。XML优于  的logback 。xml。如果使用标准 的logback 。xml配置,Spring Boot可能无法完全控制日志的初始化。</p> <p>这是logback的代码 - spring 。xml文件。</p> <pre> <code class="language-xml"><?xml version="1.0" encoding="UTF-8"?> <configuration>     <include resource="org/springframework/boot/logging/logback/base.xml"/>     <logger name="guru.springframework.controllers" level="WARN" additivity="false">         <appender-ref ref="CONSOLE"/>         <appender-ref ref="FILE"/>     </logger>     <logger name="guru.springframework.helpers" level="WARN" additivity="false">         <appender-ref ref="CONSOLE"/>         <appender-ref ref="FILE"/>     </logger> </configuration></code></pre> <p><br /> 通过更新的Spring Boot Logback配置,我们的日志输出现在如下所示:在上面的配置代码中,我们包括了 基础。第3行中的xml文件,请注意,我们没有配置任何appender。相反,我们依靠由Spring Boot提供的 CONSOLE和 FILE appender。</p> <p><img alt="记录Spring引导XML配置的输出" class="img-thumbnail" src="https://i0.wp.com/springframework.guru/wp-content/uploads/2016/04/logging_output_xml_configuration-1024x473.png?resize=863%2C399&ssl=1" /></p> <p><strong>注</strong>:Spring Boot要求 的logback - Spring。xml配置文件要在类路径上。但是,您可以将其存储在不同的位置,并使用日志记录指向它 。config属性在application.properties中。属性。</p> <h4>spring boot配置文件在日志记录中</h4> <p>在本地机器上开发时,通常将日志级别设置为 DEBUG。这将为您提供详细的日志消息供您开发使用。在生产时,它的典型设置将日志级别设置为 WARN或以上。这是为了避免在生产过程中运行时使用过多的调试信息和日志记录来填充日志。虽然日志记录非常有效,但仍然有成本。</p> <p>Spring Boot通过使用< springProfile >元素扩展用于回溯配置的Spring配置文件来解决这些要求 。使用你这个元素 的logback - spring。xml文件,您可以根据活动的spring boot配置文件选择性地包括或排除日志记录配置部分。</p> <p><strong>注意</strong>:在回弹配置中支持 < springProfile >可从SpringBoot 1.3.0.M2里程碑开始。</p> <p>以下是使用活动的Spring boot配置文件配置Logback的XML示例。</p> <p><br />  </p> <pre> <code class="language-xml"><?xml version="1.0" encoding="UTF-8"?> <configuration>     <include resource="org/springframework/boot/logging/logback/base.xml" />     <springProfile name="dev,staging">         <logger name="guru.springframework.controllers" level="DEBUG" additivity="false">             <appender-ref ref="CONSOLE" />         </logger>>     </springProfile>     <springProfile name="production">         <logger name="guru.springframework.controllers" level="WARN" additivity="false">             <appender-ref ref="FILE" />         </logger>     </springProfile> </configuration></code></pre> <p>要将配置文件传递给应用程序,请使用- Dspring运行 应用程序。档案。active = JVM参数。在上面的配置代码中,对于 dev和 staging配置文件,我们配置了上 师。springframework的。控制器记录器将DEBUG和更高级别的消息记录到 控制台。对于 生产配置文件,我们配置了相同的记录器来将WARN和更高级别的消息记录到 文件中。</p> <p>对于本地开发,在IntelliJ中,选择<strong>Run-> Edit Configurations</strong>,并在<strong>Run / Debug Configurations</strong>对话框中设置JVM参数,如下所示。</p> <p><img alt="设置用于登录IntelliJ的活动配置文件" class="img-thumbnail" src="https://i0.wp.com/springframework.guru/wp-content/uploads/2016/04/RunDebug_Configurations_Dialog.png?resize=755%2C261&ssl=1" /></p> <p>现在,当我们使用dev配置文件运行应用程序时 ,我们将看到以下日志输出。</p> <p><img alt="使用弹簧活动配置文件记录输出" class="img-thumbnail" src="https://i1.wp.com/springframework.guru/wp-content/uploads/2016/04/logging_output_springl_profile.png?resize=863%2C171&ssl=1" /></p> <p>在上面的输出中,观察IndexController的日志记录输出 。 根据dev配置文件的配置,DEBUG和更高的日志消息记录到控制台 。您可以使用生产配置文件重新启动应用程序, 以确保将 WARN和较高日志消息记录到该文件中。</p> <h4>配置文件的条件处理</h4> <p>Logback支持在Janino库的帮助下对配置文件进行条件处理。您可以使用配置文件中的 < if >, < then >和 <else >元素来定位多个环境。要执行条件处理,请将Janino依赖项添加到您的Maven POM中,像这样。</p> <pre> <code class="language-xml"><dependency>    <groupId>org.codehaus.janino</groupId>    <artifactId>janino</artifactId>    <version>2.7.8</version> </dependency></code></pre>   <pre> <code class="language-xml"><?xml version="1.0" encoding="UTF-8"?> <configuration>     <include resource="org/springframework/boot/logging/logback/base.xml" />     <springProfile name="dev,staging">         <logger name="guru.springframework.controllers" level="DEBUG" additivity="false">             <appender-ref ref="CONSOLE" />         </logger>>     </springProfile>     <springProfile name="production">     <logger name="guru.springframework.controllers" level="WARN" additivity="false">         <appender-ref ref="FILE" />     </logger>     </springProfile>     <if condition='property("spring.profiles.active").contains("dev")'>         <then>             <logger name="guru.springframework.helpers" level="DEBUG" additivity="false">                 <appender-ref ref="CONSOLE" />             </logger>         </then>         <else>             <logger name="guru.springframework.helpers" level="WARN" additivity="false">                 <appender-ref ref="FILE" />             </logger>         </else>     </if> </configuration></code></pre>   <p>完整的logback - spring。这是具有条件处理逻辑的xml文件。</p> <p> </p> <p>在上面的代码中,我们在< if >元素中指定了一个条件, 以检查当前活动的配置文件是否包含 dev。如果条件求 值为true,则< then >元素中的配置代码将 执行。在 < then >元素中,我们配置了 大师。springframework的。帮助人员将 DEBUG和更高级的消息记录到控制台。我们使用 < else >元素来配置记录器来将WARN和更高的消息记录到 日志文件中。所述 < 别的>元素执行用于比其它任何配置文件 dev的。</p> <p>当您使用生产配置文件运行应用程序 并进行访问时,两个记录器都会将 WARN和更高的消息记录到日志文件中,与此类似。<br /> <img alt="使用生产配置文件记录输出" class="img-thumbnail" src="https://i0.wp.com/springframework.guru/wp-content/uploads/2016/04/logging_output_production_profile.png?resize=642%2C319&ssl=1" /></p> <p>对于 dev配置文件,两个记录器都会将 DEBUG和更高级的消息记录到控制台,类似于此。<br /> <img alt="记录dev配置文件的输出" class="img-thumbnail" src="https://i2.wp.com/springframework.guru/wp-content/uploads/2016/04/logging_output_dev_profile.png?resize=863%2C222&ssl=1" /></p> <h4>logback自动扫描问题与spring boot</h4> <p>在的logback - spring。xml文件,您可以通过设置scan = “true”属性来启用配置的自动扫描 。启用自动扫描后,Logback扫描配置文件中的更改。对于任何更改,Logback自动重新配置它们。您可以通过将时间段传递给scanPeriod属性来指定扫描周期 ,其值以毫秒,秒,分钟或小时为单位指定。<br /> 例如,此代码告诉Logback扫描 logback - spring 。xml每10秒钟。</p> <pre> <code class="language-xml"><configuration debug="true" scan="true" scanPeriod="10 seconds" >   ... </configuration></code></pre>   <pre> <code>//Error on using auto-scan with springProfile   -ERROR in ch.qos.logback.core.joran.spi.Interpreter@4:39 - no applicable action for [springProfile],   current ElementPath  is [[configuration][springProfile]]   //Error on using auto-scan with springProperty   -ERROR in ch.qos.logback.core.joran.spi.Interpreter@12:125 - no applicable action for [springProperty],     current ElementPath  is [[configuration][springProperty]]</code></pre>   <p>Spring Boot Logback的一个限制是使用 springProfile和 springProperty,设置自动扫描结果为错误。</p> <p>由于不兼容性问题而发生错误。Spring Boot使用 JoranConfigurator子类支持 springProfile和 springProperty。不幸的是,Logback的 ReconfigureOnChangeTask不提供挂接插件。</p> <h4>结论</h4> <p>Logback的流行趋势在于开源社区。许多受欢迎的开源项目使用Logback来记录日志需求。 <a href="https://camel.apache.org/" rel="external nofollow" target="_blank" title="阿帕奇骆驼">Apache Camel</a>,<a href="http://gradle.org/" rel="external nofollow" target="_blank" title="毕业">Gradle</a>和<a href="http://www.sonarqube.org/" rel="external nofollow" target="_blank">SonarQube</a>只是几个例子。</p> <p>回溯显然具有处理复杂企业应用程序登录需求的能力。所以,难怪Spring Boot团队为默认的日志记录实现选择了Logback。正如你在这篇文章中看到的,Spring Boot团队提供了与Logback的良好集成。开箱即用,Logback可以随Spring Boot一起使用。在这篇文章中,您已经看到,随着日志需求的发展,在spring boot中配置Logback是多么容易。<br /> <br /> 完整例子1:<br />  </p> <pre> <code class="language-xml"><?xml version="1.0" encoding="UTF-8"?> <!-- scan:当此属性设置为true时,配置文件如果发生改变,将会被重新加载,默认值为true。 scanPeriod:设置监测配置文件是否有修改的时间间隔,如果没有给出时间单位,默认单位是毫秒当scan为true时,此属性生效。默认的时间间隔为1分钟。 debug:当此属性设置为true时,将打印出logback内部日志信息,实时查看logback运行状态。默认值为false。 --> <configuration scan="false" scanPeriod="60 seconds" debug="false"> <property name="filePath" value="/aos/logs/axschoolweb.log" /> <property name="fileNamePattern" value="/aos/logs/axschoolweb" /> <appender name="console" class="ch.qos.logback.core.ConsoleAppender"> <encoder> <pattern>%date{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern> </encoder> </appender> <appender name="rollingFile" class="ch.qos.logback.core.rolling.RollingFileAppender"> <file>${filePath}</file> <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy"> <fileNamePattern>${fileNamePattern}.%d{yyyy-MM-dd}.log</fileNamePattern> </rollingPolicy> <encoder> <pattern>%date{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern> </encoder> </appender> <!-- level等级顺序:error>warn>info>debug。 --> <logger name="org.springframework" level="WARN"/> <logger name="org.springframework.web" level="DEBUG"/> <logger name="org.springframework.remoting" level="WARN"/> <logger name="org.springframework.scheduling.quartz" level="WARN"/> <logger name="org.springframework.data.jpa" level="WARN"/> <logger name="org.cometd" level="WARN"/> <logger name="ch.qos.logback" level="WARN"/> <logger name="jdbc.sqltiming" level="WARN"/> <logger name="com.leftso" level="DEBUG"><!--根据具体项目配置--> <appender-ref ref="rollingFile"/> </logger> <!-- root与logger是父子关系,没有特别定义则默认为root,任何一个类只会和一个logger对应, 要么是定义的logger,要么是root,判断的关键在于找到这个logger,然后判断这个logger的appender和level。 --> <root level="DEBUG"> <appender-ref ref="console"/> <appender-ref ref="rollingFile"/> </root> </configuration></code></pre> <br /> <br /> 20171124更新=============================> <h3>logback配置打印mybaties sql日志</h3> <pre> <code class="language-xml"><logger name="net.xqlee.project.demo.dao" ><!--这里配置自己的dao(mybaties mapper接口)的包路径--> <level value="DEBUG"/> <appender-ref>console</appender-ref><!--指定一种或多种logback日志记录器--> </logger></code></pre> 如上代码片段所示,logback打开mybaties的sql打印日志需要创建一个logger并配置mybaties的dao所在包。然后将日志的等级调制DEBUG即可。日志的记录方式和其他logger一样可以配置多个。