Mybatis的配置
maven依赖
主要是依赖的添加
junit junit 4.11 test org.mybatis mybatis 3.2.6 mysql mysql-connector-java 6.0.6 log4j log4j 1.2.17
SqlMapConfig.xml
mybatis 的全局配置:
在idea中创建resources
文件夹,文件夹中创建xml文件 SqlMapConfig.xml
(文件名可以为其他),文件内容为:
其中:
- settings : 一些全局配置
- typeAlias : 别名
- environments : 数据库的连接配置
- mapper : 映射文件的配置
Log4J配置
### 设置###log4j.rootLogger = debug,stdout,D,E### 输出信息到控制抬 ###log4j.appender.stdout = org.apache.log4j.ConsoleAppenderlog4j.appender.stdout.Target = System.outlog4j.appender.stdout.layout = org.apache.log4j.PatternLayoutlog4j.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.FileAppenderlog4j.appender.D.File = E:/logs/debug.loglog4j.appender.D.Append = truelog4j.appender.D.Threshold = DEBUGlog4j.appender.D.layout = org.apache.log4j.PatternLayoutlog4j.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.FileAppenderlog4j.appender.E.File = E://logs/error.loglog4j.appender.E.Append = truelog4j.appender.E.Threshold = ERRORlog4j.appender.E.layout = org.apache.log4j.PatternLayoutlog4j.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文件配置
mapper.java 接口文件
public interface UserDao { User getOne(int userId); ListfindUserListMap();}
测试代码
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片段
and user.sex = #{userCustom.sex} and user.username LIKE '%${userCustom.username}%'