1. 第一个基于MyBatis框架实现的DAO应用

注意:本例是基于普通Java应用的实例,需要自己下载并导入依赖包。

1.配置环境

1.1 导入相应的依赖包

依赖包下载地址:
https://github.com/mybatis/mybatis-3/releases
在这里插入图片描述
下载好依赖包后,在项目依赖中将其添加。

1.2.然后我们开始要配置数据库连接环境

1.2.1在src文件下创建一个xml配置文件

在这里插入图片描述
这个配置文件中包含了pojo的别名配置,数据源配置,映射文件配置。

<?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>
 
   <typeAliases>
    <typeAlias alias="role" type="mybaits.pojo.Role"/>//关联pojo对象
   </typeAliases>
 
   <environments default="development">
     <environment id="development">
       <transactionManager type="JDBC">
         <property name="autoCommit" value="false"/>
       </transactionManager>
       
       <dataSource type="POOLED">
        <property name="driver" value="com.mysql.cj.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://localhost:3306/jdbc?&amp;useSSL=false&amp;serverTimezone=UTC"/>
        <property name="username" value="root"/>
        <property name="password" value="root"/>
       </dataSource>
     
     </environment>
   </environments>
   
   <mappers>
    <mapper resource="mybaits\mapper\RoleMapper.xml"/>//关联映射文件
   </mappers>
   
 </configuration>

1.2.2 编写获取连接的类

package mybaits.util;

import java.io.IOException;
import java.io.InputStream;
import java.util.logging.Level;

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;

public class SqlSessionFactoryUtil {
	
	private static SqlSessionFactory sqlSessionFactory=null;
	
	private static final Class CLASS_LOCK=SqlSessionFactoryUtil.class;
	
	private SqlSessionFactoryUtil() {}
	
	public static SqlSessionFactory initSqlSessionFactory() {
	    //对应配置文件路径
		String resource="mybaits-config.xml";
		InputStream inputStream=null;
		try {
			inputStream = Resources.getResourceAsStream(resource);
		}catch(IOException ex) {
			Logger.getLogger(SqlSessionFactoryUtil.class.getName()).log(null,ex);
		}
		
		synchronized(CLASS_LOCK) {
			if(sqlSessionFactory==null) {
				sqlSessionFactory=new SqlSessionFactoryBuilder().build(inputStream);
			}
		}
		return sqlSessionFactory;
	}
	
	public static SqlSession openSqlSession() {
		if(sqlSessionFactory==null) {
			initSqlSessionFactory();
		}
		return sqlSessionFactory.openSession();
	}
	
}

1.2.3.接着我们要编写对应的pojo对象和映射文件和操作接口

在这里插入图片描述
pojo

package mybaits.pojo;
public class Role {
	private Long id;
	private String roleName;
	private String note;
	public Long getId() {
		return id;
	}
	public void setId(Long id) {
		this.id = id;
	}
	public String getRoleName() {
		return roleName;
	}
	public void setRoleName(String roleName) {
		this.roleName = roleName;
	}
	public String getNote() {
		return note;
	}
	public void setNote(String note) {
		this.note = note;
	}
}

mysql创建表的语句:

mysql> create table t_role(
    -> id int,
    -> role_name varchar(40),
    -> note varchar(50));
Query OK, 0 rows affected (0.25 sec)

RoleMapper映射文件

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
 PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
 "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
 
 <mapper namespace="mybaits.mapper.RoleMapper">
 
   <select id="getRole" parameterType="long" resultType="role">
    select id,role_name as roleName,note from t_role where id = #{id}
   </select>
   
   <insert id="insertRole" parameterType="role">
     insert into t_role(role_name,note) values (#{roleName},#{note})
   </insert>
   
   <delete id="deleteRole" parameterType="long">
    delete from t_role where id = #{id}
   </delete>
 </mapper>

RoleMapper映射操作接口

package mybaits.mapper;

import mybaits.pojo.Role;

public interface RoleMapper {

	public Role getRole(Long id);
	public int deleteRole(Long id);
	public int insertRole(Role role);
}

编写主类测试:

package mybaits.main;
import java.io.IOException;
import org.apache.ibatis.session.SqlSession;

import mybaits.mapper.RoleMapper;
import mybaits.pojo.Role;
import mybaits.util.SqlSessionFactoryUtil;

public class Main {
public static void main(String[] args) throws IOException {
	SqlSession sqlSession = null;
	try {
		sqlSession = SqlSessionFactoryUtil.openSqlSession();
		RoleMapper roleMapper=sqlSession.getMapper(RoleMapper.class);
		Role role = new Role();
		role.setRoleName("testName");
		role.setNote("testNote");
		roleMapper.insertRole(role);
		sqlSession.commit();
	}catch(Exception ex) {
		System.err.println(ex.getMessage());
		sqlSession.rollback();
	}finally {
		if(sqlSession!=null) {
			sqlSession.close();
		}
	}
}
}

测试结果:
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

程序员小牧之

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值