Mybatis学习(2)第一个Mybatis程序

首先看需求,这一个Mybatis的功能是:将Student信息写入到DB中

先看一下我的项目结构:

1 基本程序

1.1 导入jar包

(1)Mybatis的核心jar包和依赖jar包

(2)Mysql的驱动jar包

(3)Junit测试的jar包,核心jar包还有依赖jar包

我已经将这些包上传到CSDN中,链接是:https://download.csdn.net/download/sdddlll/10799475

1.2 定义实体类

首先在com.test.beans创建一个Student类,与数据库中的student相对应

package com.test.beans;

public class Student {
	private Integer id;
	private String name;
	private int age;
	private double score;	
	
    //带参构造器
    //无参构造器
    //每个属性的get set方法

}

1.3 在DB中按照定义的实体类,创建相应的表

1.4 定义dao接口

在com.test.dao下创建

package com.test.dao;
import com.test.beans.Student;
public interface IStudentDao {
	//对一个表的基本操作
	void insertStu(Student student);
}

1.5 定义映射文件

什么是映射文件呢?映射文件简称为mapper,主要完成Dao层中SQL语句的映射。映射文件名字可以随意,一般都存放在dao层。这里的映射文件名字为mapper.xml。当然这里的xml文件,并不能随意写,里面有很多约束,Mybatis.jar包中定义了它的约束。因此我们在编写mapper.xml文件时,首先定义它的约束,向别人说明这个文件是一个mapper文件。我们在com.test.dao中定义这个文件,与IStudent接口同目录。

映射文件的内容是

<?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="test">
	<!-- parameterType已经定义了别名 -->
	<insert id="insertStudent" >
		insert into student(name,age,score) values(#{name},#{age},#{score})
	</insert>
</mapper>

其中约束的定义如下:

<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">

我们看里面的内容:#{}里面写入的是Student的属性名。对于parameterType类型,框架会自动根据用户执行的SqlSession方法中的参数,自动检测到,所以我们一般不指定parameterType属性

1.6 定义主配置文件

主配置文件的作用主要是,对于数据库的链接,mapper文件和IStudent接口的映射等等一些配置,它一般存放在src目录下,

第一步添加约束,

<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">

第二步配置:

  1. 配置环境,我们的程序在实际开发当中可能不止链接一个数据库,所以可以有很多个不同的环境,在这里我们只是定义了一个只在mysql中进行定义。
<?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="testEM">
		<environment id="testEM">
			<transactionManager type="JDBC"/>
			<dataSource type="POOLED">
				<property name="driver" value="${jdbc.driver}"/>
				<property name="url" value="${jdbc.url}"/>
				<property name="username" value="${jdbc.user}"/>
				<property name="password" value="${jdbc.password}"/>
			</dataSource>
		</environment>
	</environments>
	
</configuration>
  1.  
  2.  接下来注册映射文件
<!-- 注册映射文件 -->
	<mappers>
		<mapper resource="com/test/dao/mapper.xml"/>
	</mappers>

最后给出完整的mybatis.xml定义

<?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>
	<!-- 数据库的配置文件 -->
	<properties resource="jdbc.properties"/>
	
	<!-- 别名的定义 -->
	<typeAliases>
		<!-- 将保内的所有类的名字作为别名 -->
		<package name="com.test.beans"/>
		<!-- <typeAlias type="com.test.beans.Student" alias="student"/> -->
	</typeAliases>
	<!-- 配置运行环境 -->
	<environments default="testEM">
		<environment id="testEM">
			<transactionManager type="JDBC"/>
			<dataSource type="POOLED">
				<property name="driver" value="com.mysql.jdbc.driver}"/>
				<property name="url" value="jdbc:mysql://127.0.0.1:3306/test1"/>
				<property name="username" value="root"/>
				<property name="password" value="root"/>
			</dataSource>
		</environment>
	</environments>
	
	<!-- 注册映射文件 -->
	<mappers>
		<mapper resource="com/test/dao/mapper.xml"/>
	</mappers>
	
</configuration>

1.7 定义IStudent的实现类

在com.test.dao中创建一个类StudentDaoImpl类集成IStudentDao接口,在这里面只是实现了一个插入学生的代码

package com.test.dao;
import org.apache.ibatis.session.SqlSession;
import com.test.beans.Student;
import com.test.util.MybatisUtil;

public class StudentDaoImpl implements IStudentDao {
	private SqlSession sqlSession;
	
	public void insertStu(Student student) {
		try {
			sqlSession=MybatisUtil.getSqlSession();
			//4.增删改查的操作
			sqlSession.insert("insertStudent",student);
			sqlSession.commit();
		}finally{
			if(sqlSession!=null){
				sqlSession.close();
			}
		}	
	}
}

由于我们在增删改查操作时候,都需要sqlSession。那么每次都创建一个sqlsession将会非常的麻烦,因此我们定义了一个工具类MybatisUtil类:

package com.test.util;

import java.io.IOException;
import java.io.InputStream;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

public class MybatisUtil {
	
	//单例模式创建sqlSession.要设置成静态的
	
	public static SqlSession getSqlSession(){
		SqlSessionFactory factory = null;
		try {
			InputStream is = Resources.getResourceAsStream("mybatis.xml");	
			if(factory==null){
				factory=new SqlSessionFactoryBuilder().build(is);
			}			
			SqlSession sqlSession = factory.openSession();
			return sqlSession;
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}
}

1.8 定义测试类

我们在另外一个包com.test.mytest下创建一个MyTest类

package com.test.mytest;
import org.junit.Before;
import org.junit.Test;
import com.test.beans.Student;
import com.test.dao.IStudentDao;
import com.test.dao.StudentDaoImpl;
public class MyTest {
	//由于增删改查都需要StudentDaoImpl,所以将其设置全局变量。	
	private IStudentDao dao ;	
	@Before
	public void testBefore(){
		dao = new StudentDaoImpl();
	}
	
	@Test
	public void testinsertStu(){	
		Student student = new Student("张三",23,93.5);
		dao.insertStu(student);
		
	}	
}

此时,我们在testinsertStu方法的上面运行测试,就能在数据库中,插入一条新的数据。但是我们如何才能知道在Myeclipse中插入是否正确呢?因此我们再添加日志控制的文件

1.9 添加日志控制文件、

Mybatis是使用Log4j进行日志控制,其中的jar包我们已经提前导入,因此此时我们再src下面创建一个log4j.properties的文件,里面的内容如下:

##define an appender named console
log4j.appender.console=org.apache.log4j.ConsoleAppender
#The Target value is System.out or System.err
log4j.appender.console.Target=System.out
#set the layout type of the apperder
log4j.appender.console.layout=org.apache.log4j.PatternLayout
#set the layout format pattern
log4j.appender.console.layout.ConversionPattern=[%-5p] %m%n
##define a logger
##.test is mybatis.xml namespace
log4j.logger.test=debug,console

在这里需要注意最后一行:

##.test is mybatis.xml namespace
log4j.logger.test=debug,console
  1. test是在mapper.xml中定义的namespace名字
  2. debug是日志的级别、

好了,第一个Mybatis就完成了。我已经将这个例子上传:https://download.csdn.net/download/sdddlll/10800746

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值