Mybatis(二)-创建第一个应用

Mybatis(二)-第一个Mybatis程序

1.Maven配置

<dependencies>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.3.0</version>
</dependency>
</dependencies>

2.新建一个数据库表

CREATE TABLE STUDENTS
(
stud_id int(11) NOT NULL AUTO_INCREMENT,
name varchar(50) NOT NULL,
email varchar(50) NOT NULL,
dob date DEFAULT NULL,
PRIMARY KEY (stud_id)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=latin1;
/*Sample Data for the students table */
insert into students(stud_id,name,email,dob)
values (1,'Student1','student1@gmail.com','1983-06-25');
insert into students(stud_id,name,email,dob)
values (2,'Student2','student2@gmail.com','1983-06-25');

创建了一个学生表

3.XML构建SqlSessionFactory

  对于我们的Mybatis来说,每一个应用都是以SessionFactory的实例为中心的。SqlSessionFactory的实力可以通过SqlSessionFactoryBuilder获得。而SqlSessionFactoryBuilder可以从XML配置文件或者编码的方法构造出SqlSessionFactory实例。从XML文件中构建SqlSessionFactory的实例非常简单,建议使用类路径下的资源文件进行配置。Mybatis包含一个名叫Resources的工具类,它包含一些使用方法,可使从classpath或其他位置加载资源文件更加容易。

3.1配置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>
<environments default="development">
<environment id="development">
<transactionManager type="jdbc"></transactionManager>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/mybatis" />
<property name="username" value="root" />
<property name="password" value="123" />
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="cn/lz/mybatis/mappers/StudentMapper.xml"/>
</mappers>
</configuration>

3.2配置映射器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="cn.lz.mybatis.chapter2.StudentMapper">
<resultMap type="Student" id="StudentResult">
<id property="studId" column="stud_id" />
<result property="name" column="name" />
<result property="email" column="email" />
<result property="dob" column="dob" />
</resultMap>
<select id="findAllStudents" resultMap="StudentResult">
SELECT * FROM STUDENTS
</select>
<select id="findStudentById" parameterType="int" resultType="Student">
SELECT STUD_ID AS STUDID, NAME, EMAIL, DOB
FROM STUDENTS WHERE STUD_ID=#{Id}
</select>
<insert id="insertStudent" parameterType="Student">
INSERT INTO STUDENTS(STUD_ID,NAME,EMAIL,DOB)
VALUES(#{studId },#{name},#{email},#{dob})
</insert>
</mapper>

3.3创建一个Student接口

  接下来我们创建一个StudentMapper接口,其定义的方法名和Mapper XML配置文件定义的SQL映射名称相同;

  1.先创建一个Student的POJO

public class Student
{
private Integer studId;
private String name;
private String email;
private Date dob;
// setters and getters
}

2.创建映射器Mapper接口StudentMapper. 其方法签名和 StudentMapper.xml 中定义的 SQL 映射定义名相同

public interface StudentMapper
{
List<Student> findAllStudents();
Student findStudentById(Integer id);
void insertStudent(Student student);
}

3.4创建一个MybatisSqlSessionFactory单例类

private static SqlSessionFactory sqlSessionFactory;
public static SqlSessionFactory getSqlSessionFactory(){
if (sqlSessionFactory==null){
synchronized (MyBatisSqlSessionFactory.class){
if (sqlSessionFactory==null){
InputStream inputStream;
try {
inputStream= Resources.getResourceAsStream("mybatis-config.xml");
sqlSessionFactory= new SqlSessionFactoryBuilder().build(inputStream);
} catch (IOException e) {
throw new RuntimeException(e.getCause());
}
}
}
}
return sqlSessionFactory;
}
public static SqlSession openSession(){
return getSqlSessionFactory().openSession();
}

使用双例doublecheck的方式返回一个单例的SqlSession。

3.5最后我们创建一个测试类来测试我们的结果

public class StudentTest {
@Test
public void testFindAllStudents(){
SqlSession sqlSession=MyBatisSqlSessionFactory.openSession();
StudentMapper studentMapper=sqlSession.getMapper(StudentMapper.class);
List<Student> students=studentMapper.findAllStudents();
for (Student student:students){
System.out.println(student);
}
}
}

生成结果:

Student{studId=1, name=’Student1’, email=’student1@gmail.com’, dob=Sat Jun 25 00:00:00 CST 1983}

Student{studId=2, name=’Student2’, email=’student2@gmail.com’, dob=Sat Jun 25 00:00:00 CST 1983}。

4一个简单的例子如何工作的?

  在Mybatis-config.xml中配置了我们SqlSessionFactory所需要的信息,每一个数据库环境对应一个SqlSesisonFactory实例,并且这里也配置了映射文件,通过映射文件可以把我们的POJO和SQL很好的映射起来,我们通过SqlSessionFactory得到我们的session,session就是我们用来管理事务和数据库操作的,通过session得到了我们对应的Mapper,我们就可以通过Mapper映射到我们的SQL语句这样就可以执行我们的代码了。
具体代码参见github地址:https://github.com/lzggsimida123/MyBatisStuding

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值