目录
1 mybaits框架的简述
1.1 mybaits框架的作用
mybatis框架是对jdbc访问操作数据库的封装,大大简化对于数据库访问操作的代码,提高开发效率。
1.2 mybaits框架封装JDBC的核心思想
通过Mybaits对JDBC中DAO层接口进行细化:
(1)使用xml文件实现DAO层接口(将JDBC中冗余代码以xml文件代替,简化jdbc)
文件名称(自定义):
DAO名+Mapper.xml
文件内容:
<操作 id="方法名">
sql语句
</操作>
(2)自动进行对象封装(使用SqlSession对象)
从数据库中查询的结果数据,自动转化为java对象
(实现代码如下,下文会有详解)
//1 读取mybatis-config.xml配置文件
InputStream resourceAsStream = Resources.getResourceAsStream("mybatis-config.xml");
//2 获取SqlSessionFactory
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
//3 获取SqlSession
SqlSession sqlSession = sqlSessionFactory.openSession();
2 第一个Mybaits程序编写
2.1 搭建开发环境
2.1.1 添加依赖
在pom.xml添加:
(1)mysql的驱动jar
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.48</version>
</dependency>
(2)mybatis框架的核心jar包
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.6</version>
</dependency>
(3)日志log4j
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
2.1.2 编写配置文件
在resource目录下创建:
(1)log4j.properties(输出日志)
log4j.rootLogger = debug,console
log4j.appender.console=org.apache.log4j.ConsoleAppender
log4j.appender.console.Target=System.out
log4j.appender.console.layout=org.apache.log4j.PatternLayout
log4j.appender.console.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n
(2)Mybaits初始配置文件 mybatis-config.xml(对应jdbc的驱动配置和创建链接部分)
配置参数:
1.数据库相关的参数:驱动类名字、url、username、password
2. mapper文件的注册
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>
<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/ems?useSSL=false"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="UserDAOMapper.xml"/>
</mappers>
</configuration>
(3)mapper文件(实现DAO层接口)
UserDAOMapper.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.baizhiedu.dao.UserDAO">
<!--
resultType 一行查询数据 封装成什么对象
-->
<select id="queryAllUsers" resultType="com.baizhiedu.entity.User">
select id, name, password
from t_user
</select>
<!--"select id,name,password from t_user where id = ?"-->
<select id="queryUserById" resultType="com.baizhiedu.entity.User">
select id, name, password
from t_user
where id = #{id}
</select>
<select id="queryUserByNameAndPassword" resultType="com.baizhiedu.entity.User">
select id, name, password
from t_user
where name = #{name}
and password = #{password}
</select>
<delete id="delete">
delete
from t_user
where id = #{id}
</delete>
<update id="update">
update t_user
set name = #{name},
password = #{password}
where id = #{id};
</update>
<insert id="save">
insert into t_user (name,password) values (#{name},#{password});
</insert>
</mapper>
2.2 开发步骤
1.创建数据库中的表
2.创建对应的实体(entity)
package com.baizhiedu.entity;
import java.io.Serializable;
public class User implements Serializable {
private Integer id;
private String name;
private String password;
public User(Integer id, String name, String password) {
this.id = id;
this.name = name;
this.password = password;
}
public User() {
}
public User(String name, String password) {
this.name = name;
this.password = password;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", name='" + name + '\'' +
", password='" + password + '\'' +
'}';
}
}
3. DAO层接口
package com.baizhiedu.dao;
import com.baizhiedu.entity.User;
import org.apache.ibatis.annotations.Param;
import java.util.List;
public interface UserDAO {
//查询所有
public List<User> queryAllUsers();
//以单个参数查询
public User queryUserById(@Param("id") Integer id);
//以多个参数查询
public User queryUserByNameAndPassword(@Param("name") String name, @Param("password") String password);
//删除操作
public void delete(@Param("id") Integer id);
//更新操作
public void update(User user);
//
public void save(User user);
}
4. Mapper文件的配置
<?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.baizhiedu.dao.UserDAO">
<!--
resultType 一行查询数据 封装成什么对象
-->
<select id="queryAllUsers" resultType="com.baizhiedu.entity.User">
select id, name, password
from t_user
</select>
<!--"select id,name,password from t_user where id = ?"-->
<select id="queryUserById" resultType="com.baizhiedu.entity.User">
select id, name, password
from t_user
where id = #{id}
</select>
<select id="queryUserByNameAndPassword" resultType="com.baizhiedu.entity.User">
select id, name, password
from t_user
where name = #{name}
and password = #{password}
</select>
<delete id="delete">
delete
from t_user
where id = #{id}
</delete>
<update id="update">
update t_user
set name = #{name},
password = #{password}
where id = #{id};
</update>
<insert id="save">
insert into t_user (name,password) values (#{name},#{password});
</insert>
</mapper>
5.Mapper文件的注册
(1)把mapper文件的名字和路径在mybatis-config.xml进行配置
<mappers>
<mapper resource="UserDAOMapper.xml"/>
</mappers>
6.编写mybatis层
重点:
(1)SqlSessionFactory(读取mybatis-config.xml)
(2)获得SqlSession对象(将Mapper.xml 替换成 可以运行的java代码)
(1) Mybatistext:( 查询所有 )(映射到UserDao类中queryAllUsers())
package com.baizhiedu.mybatis;
import com.baizhiedu.dao.UserDAO;
import com.baizhiedu.entity.User;
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 java.io.IOException;
import java.io.InputStream;
import java.util.List;
public class MybatisTest {
public static void main(String[] args) throws IOException {
//1 读取mybatis-config.xml配置文件
InputStream resourceAsStream = Resources.getResourceAsStream("mybatis-config.xml");
//2 获取SqlSessionFactory
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
//3 获取SqlSession
SqlSession sqlSession = sqlSessionFactory.openSession();
UserDAO userDAO = sqlSession.getMapper(UserDAO.class);
List<User> users = userDAO.queryAllUsers();
for (User user : users) {
System.out.println("user = " + user);
}
}
}
(2)Mybatistext2:( 删除操作)(映射到UserDao类中delete())
package com.baizhiedu.mybatis;
import com.baizhiedu.dao.UserDAO;
import com.baizhiedu.entity.User;
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 java.io.IOException;
import java.io.InputStream;
public class MyBatisTest2 {
public static void main(String[] args) throws IOException {
InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
SqlSession sqlSession = sqlSessionFactory.openSession();
UserDAO userDAO = sqlSession.getMapper(UserDAO.class);
userDAO.delete(7);
sqlSession.commit();
//sqlSession.rollback()回滚
}
}
(3)Mybatistext3:(更新操作)(映射到UserDao类中update())
package com.baizhiedu.mybatis;
import com.baizhiedu.dao.UserDAO;
import com.baizhiedu.entity.User;
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 java.io.IOException;
import java.io.InputStream;
public class MyBatisTest3 {
public static void main(String[] args) throws IOException {
InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
SqlSession sqlSession = sqlSessionFactory.openSession();
UserDAO userDAO = sqlSession.getMapper(UserDAO.class);
User user = new User(1, "xiaopp", "123456");
userDAO.update(user);
sqlSession.commit();
//sqlSession.rollback()回滚
}
}
(4)Mybatistext4:( 增加操作)(映射到UserDao类中save())
public class MyBatisTest4 {
public static void main(String[] args) throws IOException {
InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
SqlSession sqlSession = sqlSessionFactory.openSession();
UserDAO userDAO = sqlSession.getMapper(UserDAO.class);
//提供一行数据
User user = new User("xiaoxxx", "222222");
userDAO.save(user);
sqlSession.commit();
//sqlSession.rollback()回滚
}
}