您的位置:首页 > 其它

MyBatis框架学习(二)-MyBatis入门案例

2018-02-06 12:59 621 查看

前言:这次我们学习一个MyBatis的入门案列,需求主要是初步了解MyBatis如何连接数据库,以及如何实现简单的CRUD操作.

一、准备开发环境

1.将所需要的jar包,添加到环境中




2.创建一个数据库db.sql并且创建一个student的表结构




3.创建一个配置文件mybatis-config.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>
<!-- 开启驼峰命名法规则,create_time 就等于createTime  -->
<settings>
<setting name="mapUnderscoreToCamelCase" value="true"/>
</settings>
<!-- 默认引用那个数据库环境 -->
<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://127.0.0.1:3306/mybatis" />
<property name="username" value="root" />
<property name="password" value="root" />
</dataSource>
</environment>
</environments>
<!-- SQL的映射文件 -->
<mappers>
<mapper resource="com/dqsy/mybatis/xml/StudentMapper.xml" />
</mappers>
</configuration>

4.我们创建一个映射文件StudentMapper.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.dqsy.mybatis.xml.StudentMapper">
<!--
id:表示一个SQL句柄,相当于JDBC中的statement
parametaerType:输入参数的类型,在SQL语句中,通过占位符#{}来接受参数
resultType:SQL操作的返回结果类型
-->
<!-- 单个查询 -->
<select id="getStudentById" parameterType="java.lang.Integer"
resultType="com.dqsy.mybatis.entity.Student">
select id,name,age,create_time from student where id=#{id}
</select>
<!-- 查询列表 -->
<select id="getStudentList" resultType="com.dqsy.mybatis.entity.Student">
select id,name,age,create_time from student
</select>
<!-- 添加学生 注意在这传参是java里的参数 而不是数据库里的字段名-->
<select id="addStudent" parameterType="com.dqsy.mybatis.entity.Student">
insert into student(name,age,create_time) values(#{name}, #{age}, #{createTime})
</select>
<!-- 删除学生 -->
<select id="delStudent" parameterType="java.lang.Integer">
delete from student where id = #{id}
</select>
<!-- 修改学生的数据 -->
<select id="uptStudent" parameterType="com.dqsy.mybatis.entity.Student">
update student set name=#{name}, age=#{age}, create_time=#{createTime} where id=#{id}
</select>
</mapper>

5.创建一个Student的实体类,并生成getset方法和toString方法

package com.dqsy.mybatis.entity;

import java.util.Date;

public class Student {

private int id;
private String name;
private int age;
private Date createTime;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String ge
bd40
tName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
@Override
public String toString() {
return "Student [id=" + id + ", name=" + name + ", age=" + age + ", createTime=" + createTime + "]";
}

}

6.我们先暂时常见一个MainTest的测试方法

package com.dqsy.mybatis.test;

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;

import com.dqsy.mybatis.entity.Student;

public class MainTest {

public static void main(String[] args) throws IOException {
//1.读取配置文件
String configFile = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(configFile);
//2.通过SqlSessionFactoryBuilder建立sqlSessionFactory
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
//3.通过sqlSessionFactory创建sqlSession
SqlSession sqlSession = sqlSessionFactory.openSession();
//4.通过sqlSession接口方法开执行数据库
Student stu = sqlSession.selectOne("com.dqsy.mybatis.xml.StudentMapper.getStudentById", 1);
//5.测试
System.out.println(stu);
//6.关闭sqlSession
sqlSession.close();
}

}

输出的结果为:




7.上面的这个测试方法为Main方法,有点麻烦,我可以可以写一个Junit Test来测试,实现我们简单的CRUD首先我们写一个IStudentDao的接口

package com.dqsy.mybatis.dao;

import java.util.List;

import com.dqsy.mybatis.entity.Student;

public interface IStudentDao {

public Student getStudentById(int id);
public List<Student> getStudentList();
public void addStudent(Student stu);
public void delStudent(int id);
public void uptStudent(Student stu);
}

8.实现这个接口IStudentDaoImpl

package com.dqsy.mybatis.dao.impl;

import java.util.List;

import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;

import com.dqsy.mybatis.dao.IStudentDao;
import com.dqsy.mybatis.entity.Student;

public class IStudentDaoImpl implements IStudentDao {
//通过构造方法把sqlSessionFactory加载进来
private SqlSessionFactory sqlSessionFactory;
public IStudentDaoImpl(SqlSessionFactory sqlSessionFactory){
this.sqlSessionFactory = sqlSessionFactory;
}
@Override
public Student getStudentById(int id) {
// TODO Auto-generated method stub
SqlSession  sqlSession = sqlSessionFactory.openSession();
Student stu = sqlSession.selectOne("com.dqsy.mybatis.xml.StudentMapper.getStudentById", id);
sqlSession.close();
return stu;
}

@Override
public List<Student> getStudentList() {
// TODO Auto-generated method stub
SqlSession  sqlSession = sqlSessionFactory.openSession();
List<Student> stus = sqlSession.selectList("com.dqsy.mybatis.xml.StudentMapper.getStudentList");
sqlSession.close();
return stus;
}

@Override
public void addStudent(Student stu) {
// TODO Autoerated method stub
SqlSession  sqlSession = sqlSessionFactory.openSession();
int rows = sqlSession.insert("com.dqsy.mybatis.xml.StudentMapper.addStudent", stu);
System.out.println("行数"+rows);
sqlSession.commit();
sqlSession.close();
}
@Override
public void delStudent(int id) {
// TODO Auto-generated method stub
SqlSession  sqlSession = sqlSessionFactory.openSession();
int rows = sqlSession.delete("com.dqsy.mybatis.xml.StudentMapper.delStudent", id);
System.out.println("行数"+rows);
sqlSession.commit();
sqlSession.close();
}
@Override
public void uptStudent(Student stu) {
// TODO Auto-generated method stub
SqlSession  sqlSession = sqlSessionFactory.openSession();
int rows = sqlSession.update("com.dqsy.mybatis.xml.StudentMapper.uptStudent", stu);
System.out.println("行数"+rows);
sqlSession.commit();
sqlSession.close();
}
}

9.然后就是测试文件了

package com.dqsy.mybatis.test;

import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.List;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;

import com.dqsy.mybatis.dao.IStudentDao;
import com.dqsy.mybatis.dao.impl.IStudentDaoImpl;
import com.dqsy.mybatis.entity.Student;

public class MyBatisTest {
private SqlSessionFactory sqlSessionFactory;
@Before
public void init() throws IOException{
//1.读取配置文件
String configFile = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(configFile);
//2.通过SqlSessionFactoryBuilder建立sqlSessionFactory
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
}
@Ignore
@Test
public void TestGetStudentById(){
IStudentDao stuDao = new IStudentDaoImpl(sqlSessionFactory);
System.out.println(stuDao.getStudentById(1));
}
@Ignore
@Test
public void TestGetStudentList(){
IStudentDao stuDao = new IStudentDaoImpl(sqlSessionFactory);
List<Student> stus = stuDao.getStudentList();
for(Student stu: stus){
System.out.println(stu);
}
}
//@Ignore
@Test
public void TestAddStudent(){
IStudentDao stuDao = new IStudentDaoImpl(sqlSessionFactory);
Student stu = new Student();
stu.setName("王巍");
stu.setAge(25);
stu.setCreateTime(new Date());
stuDao.addStudent(stu);
}
@Ignore
@Test
public void TestDelStudent(){
IStudentDao stuDao = new IStudentDaoImpl(sqlSessionFactory);
stuDao.delStudent(1);
}
@Test
public void TestUptStudent(){
IStudentDao stuDao = new IStudentDaoImpl(sqlSessionFactory);
Student stu = new Student();
stu.setId(5);
stu.setName("可鑫");
stu.setAge(28);
stu.setCreateTime(new Date());
stuDao.uptStudent(stu);
}
}

10.在这呢结果我就不一一截图了,我们来看看数据库




二、总结

通过这个简单的案例我们已经基本了解MyBatis的使用,以及它的配置文件,让一个简单的项目跑起来了,一个接口方法对应一个SQL语句,这就是MyBatis的简单之处,下节我们将继续学习,MyBatis的各项配置以及常见的、复杂的用法。

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: