ORM框架:对象关系映射(持久层框架)
MyBatis框架和Hibernate框架都属于ORM框架
MyBatis是一个支持普通SQL查询,存储过程和高级映射的优秀持久层框架。
MyBatis使用简单的XML或注解用于配置和原始映射,将接口和java的POJOs(Plain Old Java Objects,普通的java对象)映射成数据库中的记录
执行流程:
1.加载配置
2.SQL解析
3.SQL执行
4.结果映射
开发流程(使用步骤):
1.导包
2.建表
3.创建配置
<?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>
<!-- 属性文件 1521:Oracle默认的端口号,3306:MySQL默认的端口号-->
<properties>
<property name="jdbc.driverClassName" value="oracle.jdbc.driver.OracleDriver"/>
<property name="jdbc.url" value="jdbc:oracle:thin:@localhost:1521:orcl"/>
<property name="jdbc.username" value="mybatis"/>
<property name="jdbc.password" value="Jredu12345"/>
</properties>
<!-- <properties resource="jdbc.properties"></properties> -->
<typeAliases>
<!-- 解析类的别名 -->
<!-- <typeAlias alias="U" type="com.jereh.entity.User"/> -->
<!-- 扫描包下的所有类文件,这个包下的所有类都是简写 -->
<package name="com.jredu.entity"/>
</typeAliases>
<!-- 环境 -->
<environments default="development">
<environment id="development">
<transactionManager type="JDBC" />
<!-- 连接池 -->
<dataSource type="POOLED">
<property name="driver" value="${jdbc.driverClassName}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
</dataSource>
</environment>
</environments>
</configuration>
4.新建实体
import java.util.List;
/**
* 用户实体类
* @author Administrator
*
*/
public class User {
private int id;
private String name;
private String pwd;
private Address address;
private List<Comment> comments;
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
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 String getPwd() {
return pwd;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
public List<Comment> getComments() {
return comments;
}
public void setComments(List<Comment> comments) {
this.comments = comments;
}
@Override
public String toString() {
return "User [id=" + id + ", name=" + name + ", pwd=" + pwd
+ ", address=" + address + ", comments=" + comments + "]";
}
}
5.编写映射文件(一般与DAO层在同一个包内)
import java.util.List;
import java.util.Map;
import com.jredu.entity.User;
/**
* 用户DAO层
* @author Administrator
*
*/
public interface UserDao {
/**
* 添加数据
* @param user
* @return
*/
int insert(User user);
/**
* 更新
* @param user
* @return
*/
int update(User user);
/**
* 删除
* @param user
* @return
*/
int delete(int id);
/**
* 单条查询
* @param id
* @return
*/
User select(int id);
List<User> selectAll();
/**
* 一对一查询
* @return
*/
User findUserWithAddress(int id);
/**
* 一对一查询,重点掌握
* @return
*/
User findUserWithAddress2(int id);
/**
* 一对多查询
* @param id
* @return
*/
User findUserWithAddressAndComments(int id);
/**
* 动态SQL查询 if
* @param user
* @return
*/
User findUserByCondition(User user);
/**
* choose when otherwise
* 类似于switch,只执行一个分支
* 动态SQL查询
* choose when otherwise
* @param user
* @return
*/
User findUserByCondition2(Map<String, Object> map);
/**
* where:
* 1.添加一个where关键字
* 2.把where子句中的第一个and去掉
* @param user
* @return
*/
User findUserByCondition3(User user);
/**
* trim:
* 1.可以添加关键字
* 2.根据前缀规则可以去掉匹配到的第一个关键字
* @param user
* @return
*/
User findUserByCondition4(User user);
/**
* foreach:
* 1.可以循环添加多个参数,遍历一个集合
* @param user
* @return
*/
List<User> findUserByCondition5(Map map);
/**
* set:添加一个set关键字
* 把最后一属性的逗号去掉
* @param user
* @return
*/
int updateByCondition(User user);
/**
* 多参数
* @param name
* @param pwd
* @return
*/
User selectByCondition(String name,String pwd);
}
<?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">
<!-- namespace对应接口地址 -->
<mapper namespace="com.jredu.dao.UserDao">
<!-- 用户结果集 -->
<resultMap type="User" id="u1">
<!-- id:代表主键,只有一个 ,column:查询处理结果集的名称,不是数据库字段的名称-->
<id property="id" column="id"/>
<result property="name" column="name"/>
<result property="pwd" column="pwd"/>
<!-- 一对一关系 -->
<association property="address" javaType="Address">
<result property="id" column="address_id"/>
<result property="province" column="province"/>
<result property="city" column="city"/>
<result property="area" column="area"/>
</association>
</resultMap>
<!-- 用户结果集 -->
<resultMap type="User" id="u2">
<!-- id:代表主键,只有一个 ,column:查询处理结果集的名称,不是数据库字段的名称-->
<id property="id" column="id"/>
<result property="name" column="name"/>
<result property="pwd" column="pwd"/>
<!-- 一对一关系 -->
<association property="address" column="address_id" select="com.jredu.dao.AddressDao.select">
</association>
</resultMap>
<!-- 用户结果集 -->
<resultMap type="User" id="u3">
<!-- id:代表主键,只有一个 ,column:查询处理结果集的名称,不是数据库字段的名称-->
<id property="id" column="id"/>
<result property="name" column="name"/>
<result property="pwd" column="pwd"/>
<!-- 一对一关系 -->
<association property="address" column="address_id" select="com.jredu.dao.AddressDao.select">
</association>
<!-- 一对多关系 -->
<collection property="comments" column="id" select="com.jredu.dao.CommentDao.selectByUserId">
</collection>
</resultMap>
<!-- id:关联对应的方法(方法名) -->
<insert id="insert" parameterType="User">
insert into users values(users_seq.nextval,#{name},#{pwd})
</insert>
<update id="update" parameterType="User">
update users set name=#{name},pwd=#{pwd} where id=#{id}
</update>
<delete id="delete" parameterType="int">
delete from users where id=#{id}
</delete>
<select id="select" parameterType="int" resultType="User">
select * from users where id=#{id}
</select>
<select id="selectAll" parameterType="int" resultType="User">
select * from users
</select>
<!-- resultMap:(返回类型)上面结果集的id -->
<select id="findUserWithAddress" parameterType="int" resultMap="u1">
select u.id,u.name,u.pwd,a.id address_id,a.province,a.city,a.area from users u,address a where u.id=#{id} and u.address_id=a.id
</select>
<select id="findUserWithAddress2" parameterType="int" resultMap="u2">
select * from users where id=#{id}
</select>
<select id="findUserWithAddressAndComments" parameterType="int" resultMap="u3">
select * from users where id=#{id}
</select>
<!-- 动态SQL if-->
<select id="findUserByCondition" parameterType="User" resultType="User">
select * from users where 1=1
<if test="id>0">
and id=#{id}
</if>
<if test="name!=null">
name=#{name}
</if>
<if test="pwd!=null">
pwd=#{pwd}
</if>
</select>
<!-- choose when otherwise -->
<select id="findUserByCondition2" parameterType="Map" resultType="User">
select * from users where 1=1
<choose>
<when test="by=='id'">
and id=#{id}
</when>
<when test="by=='name'">
and name=#{name}
</when>
<otherwise>
and pwd=#{pwd}
</otherwise>
</choose>
</select>
<!-- where:代替了where关键字,会把第一个子句的and去掉(智能判断) -->
<select id="findUserByCondition3" parameterType="User" resultType="User">
select * from users
<where>
<if test="id>0">
and id=#{id}
</if>
<if test="name!=null">
name=#{name}
</if>
<if test="pwd!=null">
pwd=#{pwd}
</if>
</where>
</select>
<!-- trim -->
<select id="findUserByCondition4" parameterType="User" resultType="User">
select * from users
<trim prefix="where" prefixOverrides="and">
<if test="id>0">
and id=#{id}
</if>
<if test="name!=null">
name=#{name}
</if>
<if test="pwd!=null">
pwd=#{pwd}
</if>
</trim>
</select>
<!-- foreach -->
<select id="findUserByCondition5" parameterType="Map" resultType="User">
select * from users where id in
<foreach collection="ids" item="id" open="(" close=")" separator=",">
#{id}
</foreach>
</select>
<!-- se关键字 -->
<!-- <update id="updateByCondition" parameterType="Map">
update users
<set>
<if test="name!=unll">
name=#{name},
</if>
<if test="pwd!=null">
pwd=#{pwd},
</if>
</set>
where id=#{id}
</update> -->
<update id="updateByCondition" parameterType="Map">
update users
<set>
<if test="name!=null">
name=#{name},
</if>
<if test="pwd!=null">
pwd=#{pwd},
</if>
</set>
where id=#{id}
</update>
<select id="selectByCondition" resultType="User">
select * from users where name=#{0} and pwd=#{1}
</select>
</mapper>
6.注册映射文件(mybatis-config.xml)
<mappers>
<!-- resource:找寻对应的xml文件 -->
<!-- <mapper resource="com/jereh/dao/UserDao.xml"/> -->
<!-- class:找寻接口文件,自动匹配对应的xml文件 -->
<!-- <mapper class="com.jereh.dao.UserDao"/> -->
<!-- url:找寻磁盘目录下的对应xml文件 -->
<!-- <mapper url="file:///E:\workspaces\myeclipse\MyBatis\src\com\jereh\dao\UserDao.xml" /> -->
<!-- package:扫描包下的所有xml文件,该包下的所有映射都会匹配 -->
<package name="com.jredu.dao"/>
</mappers>
7.编写测试类
public class Test {
public static void main(String[] args) {
//配置信息地址
String resource="mybatis-config.xml";
//定义一个输入流
InputStream is=null;
//从配置文件当中读取信息
is=Test.class.getClassLoader().getResourceAsStream(resource);
//创建一个sql对象工厂
SqlSessionFactory factory=new SqlSessionFactoryBuilder().build(is);
//得到所有的sql对象
SqlSession sqlSession=factory.openSession();
//通过sqlsesion得到对象(通过getMapper方法把对应的映射文件转成具体实现)
//SQL解析
UserDao userDao=sqlSession.getMapper(UserDao.class);
//创建用户对象
User user=new User();
user.setName("小李");
user.setPwd("111111");
//添加用户
int code=userDao.insert(user);
//提交事务
sqlSession.commit();
if(code>0){
System.out.println("添加成功");
}
}
}
配置文件的基本结构:
Properties:
properties和java的.properties的配置文件有关。配置properties的resource指定.properties的路径。
在properties标签下配置property的name和value,则可以替换.properties文件中相应属性值。
typeAliases类型别名:
类型别名是Java类型的简称。
它仅仅只是关联到XML配置,简写冗长的JAVA类名。
envirotments环境:
MyBatis可以配置多个环境。这可以帮助你SQL映射对应多种数据库等。
DataSource资源:
dataSource元素使用标准的JDBC数据源接口来配置JDBC连接对象源。
MyBatis内置了三种数据源类型:
1.UNPOOLED
2.POOLED
3.JNDI
mappers映射器:
作用:告诉MyBatis去哪寻找映射SQL的语句。
可以使用类路径中的资源引用,或者使用字符,输入确切的URL引用。
四种方式:resources,url,Class,package