1、Mybatis支持普通SQL查询、存储一级高级映射的优秀持久层框架
2、Mybatis可以使用简单的XML或注解用于配置和原始映射,将接口与Java的POJO(Plain Old Java Objects)映射成数据库中的记录
3、Mybatis开发需要导入相应的jar包:mybatis-3.1.1.jar
4、Mybatis配置文件,如:mybatis.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>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC" />
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/mybatis" />
<property name="username" value="root" />
<property name="password" value="root" />
</dataSource>
</environment>
</environments>
</configuration>
5、开发实例:
- 框架:
-
JavaBean对象:
package com.djh.beans; public class User { private int id; private String name; private int age; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } @Override public String toString() { return "User [id=" + id + ", name=" + name + ", age=" + age + "]"; }
}
-
配置文件mybatis.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> <environments default="development"> <environment id="development"> <transactionManager type="JDBC" /> <dataSource type="POOLED"> <property name="driver" value="com.mysql.jdbc.Driver"/> <property name="url" value="jdbc:mysql://localhost:3306/mybatis"/> <property name="username" value="root"/> <property name="password" value="java"/> </dataSource> </environment> </environments> <!-- 注册userMapper.xml文件 --> <mappers> <mapper resource="com/djh/beans/userMapper.xml"></mapper> </mappers> </configuration>
-
持久化类对应的映射文件:userMapper.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.djh.beans.userMapper"> <insert id="insertUser" parameterType="com.djh.beans.User"> insert into users(name, age) values(#{name}, #{age}); </insert> <delete id="deleteUser" parameterType="int"> delete from users where id=#{id} </delete> <update id="updateUser" parameterType="com.djh.beans.User"> update users set name=#{name},age=#{age} where id=#{id} </update> <select id="selectUser" parameterType="int" resultType="com.djh.beans.User"> select * from users where id=#{id} </select> </mapper>
-
测试类:
package com.djh.test; import java.io.IOException; import java.io.Reader; import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; import com.djh.beans.User; public class MybatisTest{ public static void main(String[] args) throws IOException { String resource = "mybatis.xml"; //加载mybatis的配置文件(它也加载关联的映射文件) Reader reader = Resources.getResourceAsReader(resource); //构建sqlSession工厂 SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(reader); //创建能执行映射文件的sql的sqlSession SqlSession sqlSession = factory.openSession(); //映射sql的标识字符串 String statement = "com.djh.beans.userMapper" + ".selectUser"; //执行查询返回一个唯一user对象的sql User user = (User) sqlSession.selectOne(statement, new Integer(1)); System.out.println(user); System.out.println(); } }
-
运行结果:
数据库DB:
6、Mybatis使用XML与注解的方式操作DB,如下:
-
结构:
-
mybatis.xml:
db.properties:
-
Utils:
-
XML方式:
-
XMLUserDAO:
-
-
XML方式的配置:
-
-
注解方式:
-
注解接口:
-
-
注解形式的DAO:
-
-
注解形式的配置:
7、log4j的应用:
-
可以在src下加入log4j的配置文件,打印日志信息
添加jar包,如:log4j-1.2.16.jar
-
配置方式:
-
方式一(properties):
log4j.rootLogger=DEBUG, Console #Console log4j.appender.Console=org.apache.log4j.ConsoleAppender log4j.appender.Console.layout=org.apache.log4j.PatternLayout log4j.appender.Console.layout.ConversionPattern=%d [%t] %-5p [%c] - %m%n log4j.logger.java.sql.ResultSet=INFO log4j.logger.org.apache=INFO log4j.logger.java.sql.Connection=DEBUG log4j.logger.java.sql.Statement=DEBUG log4j.logger.java.sql.PreparedStatement=DEBUG
-
方式二(xml):
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE log4j:configuration SYSTEM "log4j.dtd"> <log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/"> <appender name="STDOUT" class="org.apache.log4j.ConsoleAppender"> <layout class="org.apache.log4j.PatternLayout"> <param name="ConversionPattern" value="%-5p %d{MM-dd HH:mm:ss,SSS} %m (%F:%L) \n" /> </layout> </appender> <logger name="java.sql"> <level value="debug" /> </logger> <logger name="org.apache.ibatis"> <level value="debug" /> </logger> <root> <level value="debug" /> <appender-ref ref="STDOUT" /> </root> </log4j:configuration>
-
8、数据表字段名与JavaBean属性名不一致的解决:
如:表orders(order_id, order_no, order_price), JavaBean(id, orderNo, price)
-
方式一,通过在sql中定义别名,如:
<select id="selectOrder" parameterType="int" resultType="_Order"> <!-- _Order为JavaBean"包名+类名"的别名 --> select order_id id, order_no orderNo, order_price price from orders where order_id=#{id} </select>
-
方式二:通过<resultMap>的形式,如:
<select id="selectOrderResultMap" parametersType="int" resultMap="orderResultMap"> select * from orders where order_id=#{id} </select> <resultMap type="_Order" id="orderResultMap"> <id property="id" column="order_id" /> <result property="orderNo" column="order_no" /> <result property="price" column="order_price" /> </resultMap>
9、关联表的查询:
-
一对一关联,如:
table:teacher(t_id, t_name), class(c_id, c_name, teacher_id)
-
JavaBean对象:
- Teacher(int:id, String:name)
- Classes(int:id, String:name, Teacher:teacher)
-
sql映射文件:(ClassesMapper.xml)
<!-- 方式一:嵌套结果: select * from class c, teacher t where c.teacher_id=t.t_id and c.c_id=#{id} --> <select id=*"getClass"* parameterType=*"int"* resultType=*"ClassResultMap"*> select * from class c, teacher t where c.teacher_id=t.t_id and c.c_id=#{id} </select> <reslutMap type=*"_Classes"* id=*"ClassResultMap"*> <id property=*"id"* column=*"c_id"* /> <result property=*"name"* column=*"c_name"* /> <!-- 关联表 --> <association property=*"teacher"* column=*"teacher_id"* javaType=*"_Teacher"*> <id property=*"id"* column=*"t_id"* /> <result property=*"name"* column=*"t_name"* /> </association> </reslutMap> <!-- 方式二:嵌套查询:通过执行另外一个SQL 映射语句来返回预期的复杂类型 select * from class where c_id=#{id} slect * from teacher where t_id=slect_id //select_id为上一个查询得到的teacher_id的值 --> <select id="getClasses" paramerterType="int" resultMap="ClassResultMap"> select * from class where c_id=#{id} </select> <resultMap type="_Classes" id="ClassResultMap"> <id property="id" column="c_id" /> <result property="name" column="c_name" /> <association property="teacher" column="teacher_id" javaType="_Teacher" select="getTeacher" /> <!-- _Teacher表示的是Teacher JavaBean所在的“包名+类名”的别名 --> </resultMap> <select id="getTeacher" parameterType="int" resultType="_Teacher"> select t_id id, t_name name from teacher where t_id=#{id} </select>
- association:用于一对一的关联查询
- property:对象属性的名称
- javaType:对象属性的类型
- column:所对应的外键字段名称
- select:使用另一个查询封装的结果
- association:用于一对一的关联查询
-
一对多关联:
如table:student(s_id, s_name, class_id), class(c_id, c_name, teacher_id)
-
JavaBean对象:
- Student(int: id, String: name)
- Classes(int: id, String: name, Teacher: teacher, List: students)
-
sql映射文件ClassMapper.xml:
<!-- 方式一: 嵌套结果: 使用嵌套结果映射来处理重复的联合结果的子集 SELECT * FROM class c, teacher t,student s WHERE c.teacher_id=t.t_id AND c.C_id=s.class_id AND c.c_id=1 --> <select id="getClass" parameterType="int" resultMap="ClassResultMap"> select * from class c, teacher t,student s where c.teacher_id=t.t_id and c.C_id=s.class_id and c.c_id=#{id} </select> <resultMap type="_Classes" id="ClassResultMap"> <id property="id" column="c_id"/> <result property="name" column="c_name"/> <association property="teacher" column="teacher_id" javaType="_Teacher"> <id property="id" column="t_id"/> <result property="name" column="t_name"/> </association> <!-- ofType 指定students 集合中的对象类型 --> <collection property="students" ofType ="_Student"> <id property="id" column="s_id"/> <result property="name" column="s_name"/> </collection> </resultMap> <!-- 方式二:嵌套查询:通过执行另外一个SQL 映射语句来返回预期的复杂类型 SELECT * FROM class WHERE c_id=1; SELECT * FROM teacher WHERE t_id=1 //1 是上一个查询得到的teacher_id 的值 SELECT * FROM student WHERE class_id=1 //1 是第一个查询得到的c_id 字段的值 --> <select id="getClass" parameterType="int" resultMap="ClassResultMap"> select * from class where c_id=#{id} </select> <resultMap type="_Classes" id="ClassResultMap"> <id property="id" column="c_id"/> <result property="name" column="c_name"/> <association property="teacher" column="teacher_id" javaType="_Teacher" select="getTeacher" /> <collection property="students" ofType ="_Student" column ="c_id" select ="getStudent" /> </resultMap> <select id="getTeacher" parameterType="int" resultType="_Teacher"> SELECT t_id id, t_name name FROM teacher WHERE t_id=#{id} </select> <select id="getStudent" parameterType="int" resultType="_Student"> SELECT s_id id, s_name name FROM student WHERE class_id=#{id} </select>
collection:指定一对多关联查询
ofType:指定集合中元素对象的类型
-
Others link:
https://blog.csdn.net/djh_happy/article/details/76407277