Mybatis实现数据的增删改查
什么是 MyBatis ?
MyBatis 是一款优秀的持久层框架,它支持定制化 SQL、存储过程以及高级映射。MyBatis 避免了几乎所有的 JDBC 代码和手动设置参数以及获取结果集。MyBatis 可以使用简单的 XML 或注解来配置和映射原生信息,将接口和 Java 的 POJOs(Plain Old Java Objects,普通的 Java对象)映射成数据库中的记录。
源于Mybatis官方网站点>>这里<<进入官网
如果使用IDEA工具需要导入相关依赖
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.6</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.46</version>
</dependency>
</dependencies>
对一个TbHotel表的CRUD操作
package com.kmyang.mybatis.beans;
public class TbHotel {
private int hotelId;
private String hotelName;
private String hotelImage;
private TbHotelType hotelType;
public TbHotelType getHotelType() {
return hotelType;
}
public void setHotelType(TbHotelType hotelType) {
this.hotelType = hotelType;
}
public int getHotelId() {
return hotelId;
}
public void setHotelId(int hotelId) {
this.hotelId = hotelId;
}
public String getHotelName() {
return hotelName;
}
public void setHotelName(String hotelName) {
this.hotelName = hotelName;
}
public String getHotelImage() {
return hotelImage;
}
public void setHotelImage(String hotelImage) {
this.hotelImage = hotelImage;
}
}
在Src目录下建一个mybatis的xml核心配置文件mybatis.cfg.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="jdbc.properties"/>
<!--数据库配置,default表示默认采用哪一个数据库环境-->
<environments default="development">
<!--生产环境数据库-->
<environment id="product">
<!--使用JDBC事务管理,事务控制由mybatis-->
<transactionManager type="JDBC"/>
<!--连接池配置,type为POOLED采用连接池-->
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/test?useSSL=TRUE"/>
<property name="username" value="root"/>
<property name="password" value="admin1806"/>
</dataSource>
</environment>
<!--开发环境数据库-->
<environment id=