保姆级Mybatis基础教程
Posted 3 ERROR(s)
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了保姆级Mybatis基础教程相关的知识,希望对你有一定的参考价值。
一、为什么需要Mybatis?
- 方便程序猿将数据存到数据库中。
- 传统的JDBC代码太复杂了,Mybatis是简化的自动版框架
以下是Mybatis官方对Mybatis的介绍
- 简单易学:本身就很小且简单。没有任何第三方依赖,最简单安装只要两个jar文件+配置几个sql映射文件易于学习,易于使用,通过文档和源代码,可以比较完全的掌握它的设计思路和实现。
- 灵活:mybatis不会对应用程序或者数据库的现有设计强加任何影响。 sql写在xml里,便于统一管理和优化。通过sql语句可以满足操作数据库的所有需求。
- 解除sql与程序代码的耦合:通过提供DAO层,将业务逻辑和数据访问逻辑分离,使系统的设计更清晰,更易维护,更易单元测试。
- 提供映射标签,支持对象与数据库的orm字段关系映射
- 提供对象关系映射标签,支持对象关系组建维护
- 提供xml标签,支持编写动态sql。
- sql和代码的分离,提高了可维护性。
Mybatis框架原理:
二、搭建项目框架
三、导入Mybatis依赖
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.7</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.9</version>
</dependency>
</dependencies>
<build>
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>false</filtering>
</resource>
</resources>
</build>
</project>
四、配置Mybatis主配置文件及外部配置文件
主配置文件:
<?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>
<!-- 1号位置 引入外部配置文件-->
<properties resource="db.properties"/>
<!-- 3号位置 起别名 -->
<typeAliases>
<typeAlias type="entity.t_user"/>
</typeAliases>
<!--环境配置,数据库连接信息 -->
<environments default="mydev">
<environment id="mydev">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="${driver}"/>
<property name="url" value="${url}"/>
<property name="username" value="${username}"/>
<property name="password" value="${password}"/>
</dataSource>
</environment>
<environment id="rcy">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/test?useSSL=true&useUnicode=true&characterEncoding=UTF-8"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="dao/Usermapper.xml"/>
</mappers>
</configuration>
外部资源配置文件:
#外部资源配配置文件
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/test?useSSL=true&;useUnicode=true&;characterEncoding=UTF-8
username=root
password=123456
五、根据数据库写实体类
package entity;
//实体类
public class t_user {
private Integer id;
private String loginName;
private String loginPwd;
private String realName;
public t_user(Integer id, String loginName, String loginPwd, String realName) {
this.id = id;
this.loginName = loginName;
this.loginPwd = loginPwd;
this.realName = realName;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getLoginName() {
return loginName;
}
public void setLoginName(String loginName) {
this.loginName = loginName;
}
public String getLoginPwd() {
return loginPwd;
}
public void setLoginPwd(String loginPwd) {
this.loginPwd = loginPwd;
}
public String getRealName() {
return realName;
}
public void setRealName(String realName) {
this.realName = realName;
}
@Override
public String toString() {
return "t_user{" +
"id=" + id +
", loginName='" + loginName + '\\'' +
", loginPwd='" + loginPwd + '\\'' +
", realName='" + realName + '\\'' +
'}';
}
}
六、接口和接口实现类
接口:
public interface User_mapper {
List<t_user> getUserList();
t_user getUserById(@Param("id") Integer id);
int insertInto(t_user t_user);
int upDate(t_user user);
int delete(Integer id);
t_user selectmap(Map<String, Object> map);
List<t_user> selectMohu(String value);
}
接口实现类:
- 指定约束文件
mybatis-3-mapper是文件名称dtd是是拓展名 - 约束文件的作用:限制,检查在当前文件中出现的标签,属性必须符合mybatis的要求。
- mapper 是当前文件的根标签,不能更改
- namespace:叫做命名空间,要求我用dao接口的全限定名称
<?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="dao.User_mapper">
<!-- select查询语句 -->
<select id="getUserList" resultType="entity.t_user">
<!-- id:我要执行sql的唯一语法标识,要求使用接口中的方法名称
resultType:表示结果类型,是sql执行后得到的ResultSet,
遍历这个ResultSet得到java对象的类型
要求使用值的类型的全限定名称
-->
select * from t_user ;
</select>
<select id="getUserById" parameterType="java.lang.Integer" resultType="entity.t_user">
select * from t_user where id =#{id}
</select>
<insert id="insertInto" parameterType="entity.t_user">
insert into t_user(id,loginName,loginPwd,realName) values (#{id},#{loginName},#{loginPwd},#{realName});
</insert>
<update id="upDate" parameterType="entity.t_user">
update t_user set loginName =#{loginName},loginPwd =#{loginPwd},realName =#{realName} where id=#{id};
</update>
<delete id="delete" parameterType="entity.t_user">
delete from t_user where id=#{id};
</delete>
<select id="selectmap" parameterType="java.util.Map" resultType="entity.t_user">
select * from t_user where id=#{Id};
</select>
<select id="selectMohu" resultType="t_user" parameterType="String">
select * from t_user where loginName like #{loginName};
</select>
</mapper>
七、utils工具类
获取sqlSession对象:
package utils;
//工具类
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;
//获取sqlSession
public class MybatisUtil {
/**
* 1.读取mybatis.xml配置文件
*/
private static SqlSessionFactory sqlSessionFactory;
static {
try {
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
}
public static SqlSession getSqlSession() {
return sqlSessionFactory.openSession();
}
}
八、测试
import dao.User_mapper;
import entity.t_user;
import org.apache.ibatis.session.SqlSession;
import utils.MybatisUtil;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class Test {
@org.junit.Test
public void test01(){
SqlSession sqlSession = MybatisUtil.getSqlSession();
User_mapper user_mapper=sqlSession.getMapper(User_mapper.class);
List<t_user> userList=user_mapper.getUserList();
//userList.forEach(System.out::println);
for (t_user t_user : userList) {
System.out.println(t_user);
}
}
@org.junit.Test
public void getUserById(){
SqlSession sqlSession= MybatisUtil.getSqlSession();
User_mapper mapper =sqlSession.getMapper(User_mapper.class);
t_user user = mapper.getUserById(1);
System.out.println(user);
sqlSession.close();
}
@org.junit.Test
public void insertInto(){
SqlSession sqlSession =MybatisUtil.getSqlSession();
User_mapper mapper=sqlSession.getMapper(User_mapper.class);
mapper.insertInto(new t_user(6,"lige","123456","zhonggr"));
sqlSession.commit();
sqlSession.close();
}
@org.junit.Test
public void upDate(){
SqlSession sqlSession=MybatisUtil.getSqlSession();
User_mapper mapper =sqlSession.getMapper(User_mapper.class);
mapper.upDate(new t_user(6,"drl","6666","dongruilong"));
sqlSession.commit();
sqlSession.close();
}
@org.junit.Test
public void delete(){
SqlSession sqlSession=MybatisUtil.getSqlSession();
User_mapper mapper=sqlSession.getMapper(User_mapper.class);
mapper.delete(6);
sqlSession.commit();
sqlSession.close();
}
@org.junit.Test
//用map查询
public void selectmap(){
SqlSession sqlSession =MybatisUtil.getSqlSession();
User_mapper mapper=sqlSession.getMapper(User_mapper.class);
Map<String,Object> map=new HashMap<String,Object>();
map.put("Id",1);
t_user user=mapper.selectmap(map);
System.out.println(user);
sqlSession.close();
}
@org.junit.Test
//模糊查询
public void selectMohu(){
SqlSession sqlSession=MybatisUtil.getSqlSession();
User_mapper mapper =sqlSession.getMapper(User_mapper.class);
List<t_user> user=mapper.selectMohu("%rcy%");
for (t_user t_user : user) {
System.out.println(t_user);
}
sqlSession.close();
}
}
以上是关于保姆级Mybatis基础教程的主要内容,如果未能解决你的问题,请参考以下文章