初学Mybatis
##框架的概念
框架是一个提供了可重用的公共结构的半成品。
## 主流框架介绍
Struts 2,Hibernate,Spring,SpringMVC,MyBatis.
Mybatis的介绍及其环境搭建
数据持久化的概念
将内存中的数据模型转换为存储模型。以及将存储模型转换为内存中的数据模型的统称
(也就是内存中的临时数据改为数据库中的持久话数据)
开源的数据持久层框架,内部封装JDBC访问数据的操作,支持普通的SQL查询,存储过程
和高级映射,主要思想是把SQL语句剥离出来依靠配置文件来灵活使用
ORM
ORM:对象/关系映射,是一种数据持久化技术。对象模型和关系型数据库之间建立对应关系,
提供一种机制,javaBean对象去操作数据库表中的数据(SQL语句实现的基础)
使用Mybatis的基本准备工作
1.下载jar包
2.部署jai包
3.编写核心配置文件包
4.创建实体类
5.创建Dao接口
6.创建SQL映射文件
7.编写测试类
下载jar包
Mybatis的官方网址 链接: [link]([添加链接描述](http://mybatis.org)).可以下载最新Release版本的MyBairs版本。
其他也可以再官方网站中下载到。
部署jar包
![lib下的jar包文件](https://img-blog.csdnimg.cn/2018112111140472.PNG)
编写核心配置文件
<?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>
<!-- 引入database.properties文件 -->
<properties resource="database.properties"></properties>
<!-- 配种mybatis的日志处理方式log4j-->
<settings>
<setting name="logImpl" value="LOG4J"/>
<!-- 配置自动映射级别 分别有:None:不自动映射
PARTIAL:部分自动映射
FULL:全部自动映射-->
<setting name="autoMappingBehavior" value="PARTIAL"/>
</settings>
<!-- 统一配置包名 -->
<typeAliases>
<package name="com.bdqn.entity"/>
</typeAliases>
<!-- 配置mybatis的运行环境 -->
<environments default="develop">
<environment id="develop">
<transactionManager type="JDBC"></transactionManager>
<!-- mybatis的数据源 -->
<dataSource type="POOLED">
<property name="driver" value="${driver}"/>
<property name="url" value="${url}"/>
<property name="username" value="${user}"/>
<property name="password" value="${password}"/>
</dataSource>
</environment>
</environments>
<!-- 将mapper文件引入到配置中 -->
<mappers>
<mapper resource="com/bdqn/dao/user/UserMapper.xml"/>
<mapper resource="com/bdqn/dao/addres/AdderssMapper.xml"/>
</mappers>
</configuration>
在这里一定要记得打入XML映射文件是时候要一个一个导入,
不然一个XML映射文件中一个方法报错所有方法运行不起来。
除非你觉得你肯定对。图片中改写的备注我写的很清楚。
创建实体类
package com.bdqn.entity;
import java.util.Date;
import java.util.List;
public class User {
private Integer id; //id
private String userCode; //用户编码
private String userName; //用户名称
private String userPassword; //用户密码
private Integer gender; //性别
private Date birthday; //出生日期
private String phone; //电话
private String address; //地址
private Integer userRole; //用户角色
private Integer createdBy; //创建者
private Date creationDate; //创建时间
private Integer modifyBy; //更新者
private Date modifyDate; //更新时间
/*附加属性*/
private String userRoleName;//用户的角色名称
private Role role;//用户的角色
private List<Address> addressList;//联系人集合
public List<Address> getAddressList() {
return addressList;
}
public void setAddressList(List<Address> addressList) {
this.addressList = addressList;
}
public Role getRole() {
return role;
}
public void setRole(Role role) {
this.role = role;
}
public String getUserRoleName() {
return userRoleName;
}
public void setUserRoleName(String userRoleName) {
this.userRoleName = userRoleName;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUserCode() {
return userCode;
}
public void setUserCode(String userCode) {
this.userCode = userCode;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getUserPassword() {
return userPassword;
}
public void setUserPassword(String userPassword) {
this.userPassword = userPassword;
}
public Integer getGender() {
return gender;
}
public void setGender(Integer gender) {
this.gender = gender;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public Integer getUserRole() {
return userRole;
}
public void setUserRole(Integer userRole) {
this.userRole = userRole;
}
public Integer getCreatedBy() {
return createdBy;
}
public void setCreatedBy(Integer createdBy) {
this.createdBy = createdBy;
}
public Date getCreationDate() {
return creationDate;
}
public void setCreationDate(Date creationDate) {
this.creationDate = creationDate;
}
public Integer getModifyBy() {
return modifyBy;
}
public void setModifyBy(Integer modifyBy) {
this.modifyBy = modifyBy;
}
public Date getModifyDate() {
return modifyDate;
}
public void setModifyDate(Date modifyDate) {
this.modifyDate = modifyDate;
}
}
在这里我刚学习的时候遇到一个问题,
就是当你实体类加入有参构造函数的时候。
必须要有无参构造。要细心。这个问题那时候挡住我半天。
创建DAO接口
package com.bdqn.dao.user;
import java.util.List;
import java.util.Map;
import org.apache.ibatis.annotations.Param;
import com.bdqn.entity.User;
/**
* @author hp
*
*/
public interface UserMapper {
/**
* 获得用户数量
* @return
*/
public int getUserCount();
/**
* 获得用户列表
* @return
*/
public List<User> getUserList();
/**
* 根据姓名查询
* @param UserName
* @return
*/
public List<User> getUserByName(@Param("name")String UserName);
/**
* 通过用户名和编号进行查询
* @param UserName
* @param userRole
* @return
*/
public List<User> getUserByNameAndRole(@Param("userName")String UserName,
@Param("userRole")Integer userRole);
/**
* 通过用户名和编号查询
* @param user
* @return
*/
public List<User> getUserByNameAndRole2(User user);
/**
* 用户名编号查询
* @param string
* @return
*/
public List<User> getUserByNameAndRole3(@Param("u") String string,@Param("userRole") Integer userRole);
/**
* 通过参数集合进行查询
* @param map
* @return
*/
public List<User> getUserByMap(Map<String, Object> map);
/**
* 获取用户列表(带用户角色)
* @return
*/
public List<User> selectUserList();
}
在这里要注意写入参的时候两个参数必须要加@Param起别名。
否则有时候会出现找不到内容入参为对象和单个参数也要加 @Param起别名 别名最好和传的参一致
创建SQL映射文件
<?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.bdqn.dao.user.UserMapper">
<sql id="userItem">
`id`,`userCode`,`userName`,`userPassword`,`gender`,`birthday`,`phone`,`address`,`userRole`,`createdBy`,
`creationDate`,`modifyBy`,`modifyDate`,`idPicPath`,`workPicPath`
</sql>
<select id="getUserCount" resultType="int">
<!-- 查询用户数量 -->
SELECT COUNT(1) FROM smbms_user;
</select>
<select id="getUserList" resultType="User">
SELECT
<include refid="userItem"/>
FROM smbms_user
</select>
<select id="getUserByName" parameterType="String" resultType="User">
SELECT
<include refid="userItem"/>
FROM smbms_user
WHERE userName LIKE CONCAT('%',#{name},'%')
</select>
<select id="getUserByNameAndRole" parameterType="Map" resultType="User">
SELECT
<include refid="userItem"/>
FROM smbms_user
WHERE userName LIKE CONCAT('%',#{userName},'%')
AND userRole=#{userRole}
</select>
<select id="getUserByNameAndRole2" resultType="User" parameterType="User">
SELECT
<include refid="userItem"/>
FROM smbms_user
WHERE userName LIKE CONCAT('%',#{userName},'%')
AND userRole=#{userRole}
</select>
<select id="getUserByNameAndRole3" resultType="User" parameterType="User">
SELECT
<include refid="userItem"/>
FROM smbms_user
WHERE userName LIKE CONCAT('%',#{u},'%')
AND userRole=#{userRole}
</select>
<select id="getUserByMap" resultType="User" parameterType="User">
SELECT
<include refid="userItem"/>
FROM smbms_user
WHERE userName LIKE CONCAT('%',#{uName},'%')
AND userRole=#{uRole}
</select>
<select id="selectUserList" resultMap="userRoleName">
SELECT u.*,r.roleName
FROM smbms_user u,smbms_role r
WHERE u.userRole=r.id
</select>
<resultMap type="User" id="userRoleName">
<result property="id" column="id" />
<result property="userCode" column="userCode"/>
<result property="userName" column="userName"/>
<result property="phone" column="phone"/>
<result property="userRoleName" column="roleName"/>
</resultMap>
</mapper>
头部Sql为数据库列。当你重复使用相同的列是。可以定义到这个标签然后再调用它。
<Select id ="名字尽量与接口方法名相同"
resultType="查询一般是返回对象可以包含大多数"></Select>
编写测试类
package com.bdqn.test;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
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 org.apache.log4j.Logger;
import org.junit.Test;
import com.bdqn.dao.user.UserMapper;
import com.bdqn.entity.User;
import com.bdqn.utils.MybatisUtils;
public class UserMapperTest {
private Logger log=Logger.getLogger(UserMapperTest.class);
@Test
public void getUserCountTest(){
int count=0;
SqlSession sqlSession=null;
// 1.读取mybatis-config.xml
String resource="mybatis-config.xml";
try {
InputStream is=Resources.getResourceAsStream(resource);
// 2.创建SqlSessionFactory 完成对配置文件的读取
SqlSessionFactory factory=new SqlSessionFactoryBuilder().build(is);
// 3.创建SqlSession 完成对应的操作
sqlSession=factory.openSession();
//count=sqlSession.selectOne("com.bdqn.dao.user.UserMapper.getUserCount");
count=sqlSession.getMapper(UserMapper.class).getUserCount();
log.info("用户数量为:"+count);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
// 4.关闭SqlSession
sqlSession.close();
}
return;
}
@Test
public void getUserList(){
List<User> list=new ArrayList<User>();
SqlSession sqlSession=null;
try {
sqlSession=MybatisUtils.createSqlSession();
list=sqlSession.getMapper(UserMapper.class).getUserList();
for (User user:list) {
System.out.println("用户编号为:"+user.getId()+",用户姓名为:"+user.getUserName()+"用户电话为:"+user.getPhone());
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
MybatisUtils.closeSqlSession(sqlSession);
}
}
@Test
public void getUserByNameAndRole(){
List<User> list=new ArrayList<User>();
SqlSession sqlSession=null;
String userName="张";
int userRole=2;
try {
sqlSession=MybatisUtils.createSqlSession();
list=sqlSession.getMapper(UserMapper.class).getUserByNameAndRole(userName, userRole);
for (User user:list) {
System.out.println("用户编号为:"+user.getId()+
",用户姓名为:"+user.getUserName()+
",用户角色编号"+user.getUserRole()+
",用户电话为:"+user.getPhone()+
",地址为:"+user.getAddress());
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
MybatisUtils.closeSqlSession(sqlSession);
}
}
@Test
public void getUserByNameAndRole2(){
List<User> list=new ArrayList<User>();
SqlSession sqlSession=null;
User user=new User();
user.setUserName("张");
user.setUserRole(2);
try {
sqlSession=MybatisUtils.createSqlSession();
list=sqlSession.getMapper(UserMapper.class).getUserByNameAndRole(user.getUserName(), user.getUserRole());
for (User u:list) {
System.out.println("用户编号为:"+u.getId()+
",用户姓名为:"+u.getUserName()+
",用户角色编号"+u.getUserRole()+
",用户电话为:"+u.getPhone()+
",地址为:"+u.getAddress());
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
MybatisUtils.closeSqlSession(sqlSession);
}
}
@Test
public void getUserByNameAndRole3(){
List<User> list=new ArrayList<User>();
SqlSession sqlSession=null;
User user=new User();
user.setUserName("张");
int userRole=2;
try {
sqlSession=MybatisUtils.createSqlSession();
list=sqlSession.getMapper(UserMapper.class).getUserByNameAndRole3(user.getUserName(), user.getUserRole());
for (User u:list) {
System.out.println("用户编号为:"+u.getId()+
",用户姓名为:"+u.getUserName()+
",用户角色编号"+u.getUserRole()+
",用户电话为:"+u.getPhone()+
",地址为:"+u.getAddress());
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
MybatisUtils.closeSqlSession(sqlSession);
}
}
@Test
public void getUserByMap(){
List<User> list=new ArrayList<User>();
SqlSession sqlSession=null;
Map<String, Object> map=new HashMap<String, Object>();
map.put("uName", "张");
map.put("uRole", "2");
try {
sqlSession=MybatisUtils.createSqlSession();
list=sqlSession.getMapper(UserMapper.class).getUserByMap(map);
for (User u:list) {
System.out.println("用户编号为:"+u.getId()+
",用户姓名为:"+u.getUserName()+
",用户角色编号"+u.getUserRole()+
",用户电话为:"+u.getPhone()+
",地址为:"+u.getAddress());
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
MybatisUtils.closeSqlSession(sqlSession);
}
}
@Test
public void selectUserList(){
List<User> list=new ArrayList<User>();
SqlSession sqlSession=null;
try {
sqlSession=MybatisUtils.createSqlSession();
list=sqlSession.getMapper(UserMapper.class).selectUserList();
for (User u:list) {
System.out.println("用户编号为:"+u.getId()+
",用户姓名为:"+u.getUserName()+
",用户昵称为:"+u.getUserCode()+
",用户角色编号"+u.getUserRole()+
",用户电话为:"+u.getPhone()+
",地址为:"+u.getAddress()+
",角色名称为:"+u.getUserRoleName());
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
MybatisUtils.closeSqlSession(sqlSession);
}
}
}
使用JunitTest测试 import org.junit.Test; 导入这个包。然后进行测试
小结
第一次写博文没什么经验。以后会写的越来越好。也会把自己学的有限的东西分享出来。或许不是特别好。但是积少成多。嘿嘿