mybatis简介
Mybatis是在jdbc的基础之上封装而成的持久层框架。
Mybatis是一个ORM框架。ORM(object relational mapping):对象关系型映射
搭建mybatis环境
1 <!-- 设置项目属性 -->
2 <properties>
3 <argLine>-Dfile.encoding=UTF-8</argLine>
4 <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
5 </properties>
6 <!-- 依赖管理 -->
7 <dependencies>
8 <!-- mysql驱动 -->
9 <dependency>
10 <groupId>mysql</groupId>
11 <artifactId>mysql-connector-java</artifactId>
12 <version>5.1.6</version>
13 </dependency>
14 <!-- mybatis框架 -->
15 <dependency>
16 <groupId>org.mybatis</groupId>
17 <artifactId>mybatis</artifactId>
18 <version>3.4.5</version>
19 </dependency>
20 </dependencies>
mybatis配置文件(配置连接数据库信息)
1 在src/main/resources下创建mybatisConfig.xml文件。
2
3 <?xml version="1.0" encoding="UTF-8"?>
4 <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
6 <configuration>
7 <environments default="mysqlDB">
8 <!-- 配置一个数据库连接环境 -->
9 <environment id="mysqlDB">
10 <transactionManager type="JDBC"></transactionManager>
11 <dataSource type="POOLED">
12 <!-- url -->
13 <property name="url" value="jdbc:mysql://127.0.0.1:3306/mybatis"></property>
14 <!-- name -->
15 <property name="username" value="root"></property>
16 <!-- password -->
17 <property name="password" value="root"></property>
18 <!-- driver class -->
19 <property name="driver" value="com.mysql.jdbc.Driver"></property>
20 </dataSource>
21 </environment>
22 </environments>
23 <!-- mybatis映射文件 -->
24 <mappers>
25 <mapper resource="mapper/UserEntityMapper.xml"></mapper>
26 </mappers>
27 </configuration>
主题结构:
<!ELEMENT configuration (properties?, settings?, typeAliases?, typeHandlers?, objectFactory?, objectWrapperFactory?, reflectorFactory?, plugins?, environments?, databaseIdProvider?, mappers?)>
<!ELEMENT mapper (cache-ref | cache | resultMap* | parameterMap* | sql* | insert* | update* | delete* | select* )+>
mybatis映射文件
1 <?xml version="1.0" encoding="UTF-8"?>
2 <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
3 <mapper namespace="com.offcn.mybatis.entity">
4 <!-- insert -->
5 <insert id="insertUser">
6 insert into tbl_user values(2,'scott','tiger',25)
7 </insert>
8 </mapper>
常用API
public class TestMybatis {
public static void main(String[] args) throws IOException {
// 加载配置文件
Reader reader = Resources.getResourceAsReader("mybatisConfig.xml");
// 创建构造器对象
SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
// 创建工厂
SqlSessionFactory sqlSessionFactory = builder.build(reader);
//创建执行对象
SqlSession session = sqlSessionFactory.openSession();
// 执行sql语句
session.insert("insertUser");
// 提交事务
session.commit();
session.close();
}
}
向SQL语句传参数方式
1 (1)传对象
2
3 <update id="updateUser" parameterType="UserEntity">
4 update tbl_user set
5 uname=#{uname},upass=#{upass},uage=#{uage} where
6 uid=#{uid}
7 </update>
8 9 public void updateUser() {
10 UserEntity user = new UserEntity(8, "紫衫龙王", "qkdny", 41);
11 // 创建执行对象
12 SqlSession session = sqlSessionFactory.openSession();
13 // 执行sql语句
14 session.insert("updateUser", user);
15 // 提交事务
16 session.commit();
17 session.close();
18 }
19 (2)传map对象
20 22 public void queryMap() {
23 // 构造条件
24 Map<String, Object> map = new HashMap<String, Object>();
25 map.put("name", "scott");
26 map.put("password", "tiger");
27 // 创建执行对象
28 SqlSession session = sqlSessionFactory.openSession();
29 // 执行sql语句
30 List<UserEntity> list = session.selectList("queryMap", map);
31 for (UserEntity user : list) {
32 System.out.println(user);
33 }
34 session.close();
35 }
36 <!-- 根据用户名和密码查询 -->
37 <select id="queryMap" resultType="UserEntity" parameterType="java.util.Map">
38 SELECT uid,uname,upass,uage from tbl_user where uname=#{name} and upass=#{password}
39 </select>
40 (3)直接传变量
41 42 public void queryById() {
43 // 创建执行对象
44 SqlSession session = sqlSessionFactory.openSession();
45 // 执行sql语句
46 UserEntity user = (UserEntity) session.selectOne("queryById", 5);
47 System.out.println(user);
48 session.close();
49 }
50 <select id="queryById" parameterType="int" resultType="UserEntity">
51 SELECT uid,uname,upass,uage from tbl_user where uid=#{uid}
52 </select>
使用实体类别名
1 <typeAliases>
2 <!-- 设置实体类别名 --> 要根据属性顺序设置该属性,不然配置文件报错
3 <typeAlias type="com.offcn.mybatis.entity.UserEntity" alias="UserEntity"></typeAlias>
4 </typeAliases>
5
6 <insert id="insertUserWithParam" parameterType="UserEntity">//此处就可以使用别名了
7 insert into tbl_user(uid,uname,upass,uage) values(#{uid},#{uname},#{upass},#{uage})
8 </insert>
获取sql结果的方式
获取对象
<!-- query id resultType:设定返回值-->
<select id="queryById" parameterType="int" resultType="UserEntity">
SELECT uid,uname,upass,uage from tbl_user where uid=#{uid}
</select>
@Test
public void queryById() {
// 创建执行对象
SqlSession session = sqlSessionFactory.openSession();
// 执行sql语句,获取对象
UserEntity user =(UserEntity)session.selectOne("queryById", 5);
System.out.println(user);
session.close();
}
获取集合
<!-- query All -->
<select id="queryAll" resultType="UserEntity">
SELECT uid,uname,upass,uage from tbl_user
</select>
@Test
public void queryAll() {
// 创建执行对象
SqlSession session = sqlSessionFactory.openSession();
// 执行sql语句,获取list集合
List<UserEntity> list=session.selectList("queryAll");
for(UserEntity user:list) {
System.out.println(user);
}
session.close();
}
简单日志使用
1 导入log4j依赖
2
3 <dependency>
4 <groupId>log4j</groupId>
5 <artifactId>log4j</artifactId>
6 <version>1.2.15</version>
7 </dependency>
8
9 resources下创建日志文件log4j.properties
10
11 ### set log levels ###
12 log4j.rootLogger = debug,stdout,log
13 #, log, index, D, I, W, E
14
15 ### print log to console ###
16 log4j.appender.stdout = org.apache.log4j.ConsoleAppender
17 log4j.appender.stdout.Target = System.out
18 log4j.appender.stdout.layout = org.apache.log4j.PatternLayout
19 log4j.appender.stdout.layout.ConversionPattern = %d %p [%c] - <%m>%n
20
21 ### create log to file ###
22 log4j.appender.log = org.apache.log4j.DailyRollingFileAppender
23 log4j.appender.log.File = /logs/log.log
24 log4j.appender.log.Append = true
25 log4j.appender.log.layout = org.apache.log4j.PatternLayout
26 log4j.appender.log.layout.ConversionPattern= %d %p [%c] - <%m>%n
27
28
29 # Control logging for other open source packages
30 log4j.logger.net.sf.navigator=ERROR
31 log4j.logger.net.sf.acegisecurity=WARN
32 log4j.logger.net.sf.acegisecurity.intercept.event.LoggerListener=WARN
33 log4j.logger.org.apache.commons=ERROR
34 log4j.logger.org.apache.struts=WARN
35 log4j.logger.org.displaytag=ERROR
36 log4j.logger.org.springframework=WARN
37 log4j.logger.org.apache.velocity=WARN
38
39
40 # SqlMap logging configuration...
41 log4j.logger.com.ibatis=debug
42 log4j.logger.com.ibatis.db=debug
43 log4j.logger.com.ibatis.common.jdbc.SimpleDataSource=debug
44 log4j.logger.com.ibatis.sqlmap.engine.cache.CacheModel=debug
45 log4j.logger.com.ibatis.sqlmap.engine.impl.SqlMapClientImpl=debug
46 log4j.logger.com.ibatis.sqlmap.engine.builder.xml.SqlMapParser=debug
47 log4j.logger.com.ibatis.common.util.StopWatch=debug
48
49 log4j.logger.java.sql.Connection=debug
50 log4j.logger.java.sql.Statement=error
51 log4j.logger.java.sql.PreparedStatement=debug
52 log4j.logger.java.sql.ResultSet=error
53
54 日志级别
55 A:off 最高等级,用于关闭所有日志记录。
56 B:fatal 指出每个严重的错误事件将会导致应用程序的退出。
57 C:error 指出虽然发生错误事件,但仍然不影响系统的继续运行。
58 D:warn 表明会出现潜在的错误情形。
59 E:info 一般和在粗粒度级别上,强调应用程序的运行全程。
60 F:debug 一般用于细粒度级别上,对调试应用程序非常有帮助。
61 G:all 最低等级,用于打开所有日志记录。