Mybatis的配置
maven依赖
主要是依赖的添加
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.2.6</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>6.0.6</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
</dependencies>
SqlMapConfig.xml
mybatis 的全局配置:
在idea中创建resources
文件夹,文件夹中创建xml文件 SqlMapConfig.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>
<settings>
<setting name="mapUnderscoreToCamelCase" value="true"/>
<setting name="lazyLoadingEnabled" value="true"/>
</settings>
<typeAliases>
<typeAlias type="com.justin.pojo.User" alias="user"/>
</typeAliases>
<environments default="local">
<environment id="local">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<!-- mysql连接的依赖包是高版本的情况下,后面要加上具体的配置信息-->
<property name="url" value="jdbc:mysql://localhost:3306/mybatis?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="user-mapper.xml"/>
</mappers>
</configuration>
其中:
- settings : 一些全局配置
- typeAlias : 别名
- environments : 数据库的连接配置
- mapper : 映射文件的配置
Log4J配置
### 设置###
log4j.rootLogger = debug,stdout,D,E
### 输出信息到控制抬 ###
log4j.appender.stdout = org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target = System.out
log4j.appender.stdout.layout = org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern = [%-5p] %d{yyyy-MM-dd HH:mm:ss,SSS} method:%l%n%m%n
### 输出DEBUG 级别以上的日志到文件F://logs/debug.log ###
log4j.appender.D = org.apache.log4j.FileAppender
log4j.appender.D.File = E:/logs/debug.log
log4j.appender.D.Append = true
log4j.appender.D.Threshold = DEBUG
log4j.appender.D.layout = org.apache.log4j.PatternLayout
log4j.appender.D.layout.ConversionPattern = %d{yyyy-MM-dd HH:mm:ss} [ %t:%r ] - [ %p ] %m%n
### 输出ERROR 级别以上的日志到文件F://logs/error.log ###
log4j.appender.E = org.apache.log4j.FileAppender
log4j.appender.E.File = E://logs/error.log
log4j.appender.E.Append = true
log4j.appender.E.Threshold = ERROR
log4j.appender.E.layout = org.apache.log4j.PatternLayout
log4j.appender.E.layout.ConversionPattern = %d{yyyy-MM-dd HH:mm:ss} [ %t:%r ] - [ %p ] %m%n
注释:
测试代码:
public class TestFirst {
private static Logger logger = Logger.getLogger(TestFirst.class);
public static void main(String[] args){
// 记录debug级别的信息
logger.debug("This is debug message.");
// 记录info级别的信息
logger.info("This is info message.");
// 记录error级别的信息
logger.error("This is error message.");
}
}
mapper.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.justin.first.UserDao">
<resultMap id="userListResultMap" type="user">
<!--id是主键 -->
<id column="id" property="id"/>
<result column="username" property="username"/>
<result column="sex" property="sex"/>
</resultMap>
<!-- id 为接口定义的方法名 resultType 为实体类的全类名 #{userId} 中的参数和方法名一致 -->
<select id="getOne" resultType="com.justin.pojo.User">
select * from users where id = #{userId}
</select>
<select id="findUserListMap" resultMap="userListResultMap">
SELECT id,username,sex FROM users;
</select>
</mapper>
mapper.java 接口文件
public interface UserDao {
User getOne(int userId);
List<User> findUserListMap();
}
测试代码
public class TestFirst {
public static void main(String[] args) {
try {
testUserSelect();
} catch (IOException e) {
e.printStackTrace();
}
}
private static void testUserSelect() throws IOException {
SqlSessionFactory factory = new SqlSessionFactoryBuilder()
.build(Resources.getResourceAsStream("mybatis-config.xml"));
SqlSession session = factory.openSession();
//mybatis的映射文件
UserDao dao = session.getMapper(UserDao.class);
User one = dao.getOne(1);
System.out.println(one);
}
}
动态sql
使用if/where/trim/set/choose(when,otherwise)/foreach等动态的配置sql语句
sql片段
<!--定义sql片段
id是sql片段的唯一标识,便于下面语句的引用。
通常把SQL片段设计成基于单表来定义sql片段,这样话这个sql片段可重用性才高。
注意:在sql片段中不要包括 where
-->
<sql id="query_user_where">
<if test="userCustom!=null">
<if test="userCustom.sex!=null and userCustom.sex!=''">
and user.sex = #{userCustom.sex}
</if>
<if test="userCustom.username!=null and userCustom.username!=''">
and user.username LIKE '%${userCustom.username}%'
</if>
</if>
</sql>
引用sql片段
<select id="findUserWithDynamic" resultType="user">
<where>
<!-- 引用sql片段 的id,如果refid指定的id不在本mapper文件中,需要前边加namespace -->
<include refid="query_user_where"/>
<!-- 在这里还可以引用其它的sql片段 -->
</where>
</select>
使用if/where
<select id="findUserList" parameterType="com.justin.pojo.UserQueryVo"
resultType="com.justin.pojo.User">
SELECT * FROM users
<!--
where可以自动去掉条件中的第一个and
-->
<where>
<include refid="query_user_where"/>
</where>
</select>