Mybatis-使用注解开发
1.所需maven依赖
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.1</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.2</version>
</dependency>
2.工具类(连接数据库)
package com.wqs.untill;
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 java.io.IOException;
import java.io.InputStream;
public class MybatisUntill {
private static SqlSessionFactory sqlSessionFactory;
static {
try {
//使用mybatis获取sqlsessionfactory对象
String resourse="mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resourse);
sqlSessionFactory=new SqlSessionFactoryBuilder().build(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
}
public static SqlSession getSqlSession(){
return sqlSessionFactory.openSession();
}
}
3.mybatis-config配置文件
<?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>
<settings>
<setting name="logImpl" value="STDOUT_LOGGING"/>
</settings>
<typeAliases>
<typeAlias alias="User" type="com.wqs.pojo.User"></typeAlias>
</typeAliases>
<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/mybatis?useSSL=true&useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper class="com.wqs.dao.UserDao"></mapper>
</mappers>
</configuration>
4.注解在接口上实现
package com.wqs.dao;
import com.wqs.pojo.User;
import org.apache.ibatis.annotations.Select;
import java.util.List;
public interface UserDao {
@Select("select * from users")
List<User> getAllUser();
}
5.测试类
import com.wqs.dao.UserDao;
import com.wqs.pojo.User;
import com.wqs.untill.MybatisUntill;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
import java.util.List;
public class UserMapperTest {
@Test
public void getAllUser(){
SqlSession sqlSession = MybatisUntill.getSqlSession();
UserDao mapper = sqlSession.getMapper(UserDao.class);
List<User> allUser = mapper.getAllUser();
for (User user : allUser) {
System.out.println(user);
}
sqlSession.close();
}
}