最近呢,学习了mybatis的相关内容,就写下了这篇博客来记录顺便复习一下如何使用Mybatis来进行简单的sql语句查询。希望我写的这篇博客能帮助大家。有问题大家可以提出来,一起进步。
先来看看我的分包,一个好的分包能够让你更好的整理思路,大家要养成分包的习惯哦。
driver=com.mysql.cj.jdbc.Driver url=jdbc:mysql://localhost:3306/mybatis?useSSL=false&serverTimezone=Hongkong&characterEncoding=utf-8&autoReconnect=true username=root password=201225qq
有没有觉得很眼熟?没错!在使用JDBC时我们也有这个步骤哦
我们在核心配置文件使用<properties resource="db.properties"/>标签,就可以以引入外部的db.properties文件了。
<?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:核心配置文件--> <configuration> <!-- 引入外部配置文件--> <properties resource="db.properties"/> <typeAliases> <typeAlias type="com.xxx.pojo.User" alias="User"/> </typeAliases> <environments default="development"> <environment id="development"> <transactionManager type="JDBC" /> <dataSource type="POOLED"> <property name="driver" value="${driver}" /> <property name="url" value="${url}"/> <property name="username" value="${username}" /> <property name="password" value="${password}" /> </dataSource> </environment> </environments> <!-- 映射器--> <mappers> <mapper resource="com/xxx/mapper/UserMapper.xml"/> </mappers> </configuration>
public class MybatisUtils { private static SqlSessionFactory sqlSessionFactory; static { try { //使用mybatis第一步,获取SqlSessionFactory对象 String resource = "mybatis-config.xml"; InputStream inputStream = Resources.getResourceAsStream(resource); sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); } catch (IOException e) { e.printStackTrace(); } } //有了 sqlSessionFactoryl,我们就可以从中获得sqlSession实例; 。 //SqlSession完全包含了面向数据库执行sql命令的所有方法 public static SqlSession getSqlSession() { return sqlSessionFactory.openSession(); } }
public class User { private int id; private String name; private String pwd; public User() { } public User(int id, String name, String pwd) { this.id = id; this.name = name; this.pwd = pwd; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPwd() { return pwd; } public void setPwd(String pwd) { this.pwd = pwd; } @Override public String toString() { return "User{" + "id=" + id + ", name='" + name + '\'' + ", pwd='" + pwd + '\'' + '}'; } }
public interface UserMapper { User getUserById(int id); }
这里的占位符使用的是 #{} ,而不是JDBC中的 ?
<?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.xxx.mapper.UserMapper"> <select id="getUserById" resultType="com.xxx.pojo.User" parameterType="int"> select * from mybatis.user where id=#{id} </select> </mapper>
@Test public void test2(){ SqlSession sqlSession = MybatisUtils.getSqlSession(); UserMapper mapper = sqlSession.getMapper(UserMapper.class); User user = mapper.getUserById(1); System.out.println(user); sqlSession.close(); }
成功通过id查询~