mybatis的使用
创建dao接口,以及需要用数据库实现的方法
package com. lin. dao ;
import com. lin. bean. employee ;
public interface EmployeeDao {
public employee getEmpById ( Integer id) ;
}
负责总的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>
< environments default = " development" >
< environment id = " development" >
< transactionManager type = " JDBC" />
< dataSource type = " POOLED" >
< property name = " driver" value = " com.mysql.cj.jdbc.Driver" />
< property name = " url" value = " jdbc:mysql://localhost:3306/database?useUnicode=true& characterEncoding=UTF-8& serverTimezone=GMT%2B8& useSSL=false& allowMultiQueries=true" />
< property name = " username" value = #{username}/>
< property name = " password" value = #{password}/>
</ dataSource>
</ environment>
</ environments>
< mappers>
< mapper resource = " mybatisToSql.xml" />
</ mappers>
</ configuration>
在idea中创建两个mybatis的配置文件与每一个dao类相映射的配置文件,创建配置文件以后,无需在java程序中实现该类即可调用方法
<! DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
< mapper namespace = " com.lin.dao.EmployeeDao" >
< select id = " getEmpById" resultType = " com.lin.bean.employee" >
select * from t_employee where id = #{id}
</ select>
</ mapper>
在程序中利用mybatis与数据库建立连接,并进行操作
public class test {
@Test
public void test ( ) throws IOException {
String resource = "mybatis.xml" ;
InputStream inputStream = Resources . getResourceAsStream ( resource) ;
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder ( ) . build ( inputStream) ;
employee em;
SqlSession sqlsession = sqlSessionFactory. openSession ( ) ;
try {
EmployeeDao employeeDao = sqlsession. getMapper ( EmployeeDao . class ) ;
em = employeeDao. getEmpById ( 1 ) ;
} finally {
sqlsession. close ( ) ;
}
System . out. println ( em) ;
}
}