Mybatis 连接 XuguDB 示例程序
📄字数 3.1K
👁️阅读量 加载中...
本文档将介绍如何使用 Mybatis v3.5.10 框架操作 XuguDB。
提示
- XuguDB-JDBC 与 Mybatis 框架完全兼容,可以直接使用 Mybatis 框架操作 XuguDB
- 示例代码 xugu-mybatis-demo 克隆/下载
一、导入 Mybatis
项目到 IDEA 中
- 使用 Maven 导入
Mybatis
依赖
在 pom.xml
文件中加入以下信息
xml
<!-- 导入 Mybatis 框架 -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.10</version>
</dependency>
<!-- 导入 XuguDB-JDBC 驱动 -->
<dependency>
<groupId>com.xugudb</groupId>
<artifactId>xugu-jdbc</artifactId>
<version>12.3.4</version>
</dependency>
<!-- 导入 druid 连接池 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.2.20</version>
</dependency>
- 使用 Gradle 导入
Mybatis
依赖
在 build.gradle
中加入以下信息
txt
//导入 Mybatis 框架
implementation("org.mybatis:mybatis:3.5.10")
//导入 XuguDB-JDBC 驱动
implementation("com.xugudb:xugu-jdbc:12.3.4")
//导入 druid 连接池
implementation("com.alibaba:druid:1.2.20")
二、连接示例程序
- 在
src/main/resources/mybatis-config.xml
配置文件中设置Mybatis
参数信息,如下所示:
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>
<!--配置文件地址 -->
<properties resource="local-xugu.properties" />
<settings>
<!-- 开启驼峰命名自动映射 -->
<setting name="mapUnderscoreToCamelCase" value="true"/>
</settings>
<!-- 类型别名 -->
<typeAliases>
<!-- druid 连接池 -->
<typeAlias type="com.xugu.datasource.DruidDataSourceFactory" alias="druid" />
</typeAliases>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC" />
<!-- 配置数据库连接信息 -->
<!-- 使用druid连接池 -->
<dataSource type="druid">
<!--这里会替换为local-xugu.properties中的对应字段的值 -->
<property name="driver" value="${driver}" />
<property name="url" value="${url}" />
<property name="username" value="${username}" />
<property name="password" value="${password}" />
<!-- 配置初始化大小、最小、最大 -->
<property name="initialSize" value="1" />
<property name="minIdle" value="1" />
<property name="maxActive" value="10" />
<!-- 配置获取连接等待超时的时间 -->
<property name="maxWait" value="10000" />
</dataSource>
</environment>
</environments>
<!--SQL映射文件,mybatis的核心 -->
<mappers>
<mapper resource="mybatis/mapper/StudentMapper.xml" />
</mappers>
</configuration>
提示
更多配置信息参考:MyBatis 官网配置信息
- 在数据库创建测试表
sql
CREATE TABLE "STUDENT" (
"ID" INT IDENTITY(1,1) NOT NULL,
"NAME" VARCHAR(200) DEFAULT NULL,
"AGE" TINYINT DEFAULT NULL,
PRIMARY KEY ("ID")
);
- 在
src/main/java/com/xugu/datasource/DruidDataSourceFactory.java
中配置连接池信息
java
public class DruidDataSourceFactory implements DataSourceFactory {
/**
* 连接池属性
*/
private Properties props;
@Override
public void setProperties(Properties props) {
this.props = props;
}
/**
* 初始化druid数据源
*/
@Override
public DataSource getDataSource() {
DruidDataSource datasource = new DruidDataSource();
//驱动名
datasource.setDriverClassName(this.props.getProperty("driver"));
//数据库连接串
datasource.setUrl(this.props.getProperty("url"));
//用户名
datasource.setUsername(this.props.getProperty("username"));
//密码
datasource.setPassword(this.props.getProperty("password"));
//初始化时建立物理连接的个数。初始化发生在显示调用init方法,或者第一次getConnection时
datasource.setInitialSize(Integer.parseInt(this.props.getProperty("initialSize")));
//最小连接池数量
datasource.setMinIdle(Integer.parseInt(this.props.getProperty("minIdle")));
//最大连接池数量
datasource.setMaxActive(Integer.parseInt(this.props.getProperty("maxActive")));
//获取连接时最大等待时间
datasource.setMaxWait(Long.parseLong(this.props.getProperty("maxWait")));
try {
datasource.init();
} catch (SQLException e) {
throw new RuntimeException(e);
}
return datasource;
}
}
- 创建与数据库表对应的实体类:
src/main/java/com/xugu/entity/StudentEntity.java
java
public class StudentEntity implements Serializable {
private static final long serialVersionUID = 1L;
private Integer id;
private String name;
private Integer age;
public StudentEntity() {}
public StudentEntity(String name, Integer age) {
this.name = name;
this.age = age;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder("StudentEntity{");
sb.append("id=").append(id);
sb.append(", name='").append(name).append('\'');
sb.append(", age=").append(age);
sb.append('}');
return sb.toString();
}
}
- 创建数据库访问接口:
src/main/java/com/xugu/mapper/StudentMapper.java
java
public interface StudentMapper {
//根据名称获取对象列表
List<StudentEntity> getAllStudent();
//插入对象,返回插入条数
int addStudent(StudentEntity student);
}
- 创建 MyBatis 映射文件:
src/main/resources/mybatis/mapper/StudentMapper.xml
xml
<?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.xugu.mapper.StudentMapper">
<!--使用Statement方式访问数据库,参数必须使用${}样式,字符串参数需使用引号-->
<select id="getAllStudent" statementType="STATEMENT" resultType="com.xugu.entity.StudentEntity">
SELECT id,name,age FROM student;
</select>
<!-- 向数据库插入数据 -->
<insert id="addStudent" parameterType="com.xugu.entity.StudentEntity" useGeneratedKeys="true" keyProperty="id">
INSERT INTO student(name,age) VALUES(#{name}, #{age})
</insert>
</mapper>
- 创建 MyBatis 测试类:
src/main/java/com/xugu/test/TestMyBatisDemo.java
java
public class TestMyBatisDemo {
public static void main(String[] args) throws IOException {
//加载 MyBatis 配置信息
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(Resources.getResourceAsReader("mybatis-config.xml"));
//获取 SqlSession 对象
SqlSession session = factory.openSession(true);
//获取 StudentMapper 对象
StudentMapper mapper = session.getMapper(StudentMapper.class);
//向表中插入三条数据
mapper.addStudent(new StudentEntity("张三",15));
mapper.addStudent(new StudentEntity("李四",16));
mapper.addStudent(new StudentEntity("王五",15));
//查询表中的数据并输出
List<StudentEntity> allStudent = mapper.getAllStudent();
for (StudentEntity studentEntity : allStudent) {
System.out.println(studentEntity);
}
}
}
三、常见问题&解决办法
- 数据库驱动:确认 XuguDB-JDBC 驱动正确导入项目
- 配置参数:MyBatis 的配置文件直接影响 MyBatis 行为的设置和属性信息,对于不熟悉的配置信息可参考MyBatis 官网配置信息