本文将阐述mybatis中原始dao方式的实现。
1、环境约束
- win10 64位操作系统
- idea2018.1.5
- jdk-8u162-windows-x64
- mybatis3.2.8
- mysql 6.5
2、前提约束
- 完成idea中创建mybatis项目 https://www.jianshu.com/p/86db0901156f
请读者注意自己数据库账号密码驱动和url的适配。
3、操作步骤
- 创建一个t_user
create table t_user(id int,name varchar(20));
insert into t_user(id,name) values(1,'ali');
insert into t_user(id,name) values(2,'xiaoli');
insert into t_user(id,name) values(3,'zhangli');
- 在src/main/java中创建net.wanho.User.java:
public class User{
private int id;
private String name;
...
}
- 在src/main/java中创建net.wanho.UserDao.java:
import net.wanho.User;
import org.apache.ibatis.annotations.Select;
import java.util.List;
public interface UserDao {
@Select("select * from t_user")
List<User> query();
}
- 在src/main/java中创建net.wanho.UserDaoImpl.java:
import net.wanho.User;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import java.util.List;
public class UserDaoImpl implements UserDao {
private SqlSessionFactory sqlsessionFactory;
public UserDaoImpl(SqlSessionFactory sqlsessionFactory) {
this.sqlsessionFactory = sqlsessionFactory;
}
@Override
public List<User> query() {
SqlSession sqlSession = sqlsessionFactory.openSession();
List<User> list = sqlSession.selectList("query");
sqlSession.close();
return list;
}
}
- 在src/java/resources下创建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="environment">
<environment id="environment">
<transactionManager type="JDBC"></transactionManager>
<dataSource type="POOLED">
<property name="url" value="jdbc:mysql://localhost:3306/test"></property>
<property name="driver" value="com.mysql.jdbc.Driver"></property>
<property name="username" value="root"></property>
<property name="password" value="123456"></property>
</dataSource>
</environment>
</environments>
<mappers>
<mapper class="net.wanho.UserDao"></mapper>
</mappers>
</configuration>
- 在src/main/java文件夹下创建Test.java
import net.wanho.entity.User;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import java.io.InputStream;
import java.util.List;
public class Test {
public static void main(String[] args) throws Exception{
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder()
.build(inputStream);
UserDao userDao = new UserDaoImpl(sqlSessionFactory);
List<User> list = userDao.query();
System.out.println(list);
}
}
以上就是mybatis中原始dao的实现方式,用的较少,了解即可。