- 添加 mybatis 、 mysql-connector-java 引用
<dependencies>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.9</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>6.0.6</version>
</dependency>
</dependencies>
- 添加 mybatis-config.xml 文件,添加连接信息
注意 时区,&在xml中需要使用&代替
最新的驱动改成com.mysql.cj.jdbc.Driver
jdbc:mysql://localhost:3306/test?serverTimezone=UTC&characterEncoding=utf-8
- 在 mybatis-config.xml 文件中添加xml和接口命名空间映射mappers
<?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/test?serverTimezone=UTC&characterEncoding=utf-8" />
<property name="username" value="root" />
<property name="password" value="" />
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="BlogMapper.xml"/>
<mapper class="com.example.mybatis3.BlogMapper"></mapper>
</mappers>
</configuration>
- 创建数据库、实体类、添加一条数据记录
CREATE TABLE `blog` (
`Id` VARCHAR(50) NULL DEFAULT NULL COLLATE 'latin1_swedish_ci',
`Name` VARCHAR(50) NULL DEFAULT NULL COLLATE 'utf8_bin'
)
COLLATE='utf8_bin'
ENGINE=InnoDB
;
INSERT INTO `test`.`blog` (`Id`, `Name`) VALUES ('1', '世界之大');
public class Blog {
public String Id;
private String Name;
public String getBlog() {
return Id;
}
public void setBlog(String blog) {
Id = blog;
}
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
}
- 添加测试代码
public class App {
public static void main(String[] args) throws IOException {
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
try (SqlSession session = sqlSessionFactory.openSession()) {
Blog blog = (Blog) session.selectOne("com.example.mybatis3.BlogMapper.selectBlog", 1);
System.out.print(blog.getName());
}
try (SqlSession session = sqlSessionFactory.openSession()) {
BlogMapper mapper = session.getMapper(BlogMapper.class);
Blog blog2 = mapper.selectBlog(1);
System.err.print(blog2.getName());
}
}
}
备注
上面方式2代码是使用接口BlogMapper 【对应Dao】中添加注解来执行sql的,需要在mybatis-config.xml 中添加
<mapper class="com.example.mybatis3.BlogMapper"></mapper>
可以将其去掉,但在BlogMapper.xml中的 namespace="com.example.mybatis3.BlogMapper"和接口类一致。id名与方法名一致即可使用对应xml的sql。
BlogMapper mapper = session.getMapper(BlogMapper.class);
项目目录结构
|