回顾jdbc
public class FindByJdbc {
public static void main(String[] args) {
Connection connection = null;
PreparedStatement statement = null;
ResultSet set = null;
try {
//加载驱动
Class.forName("com.mysql.jdbc.Driver");
//通过驱动获取连接
connection = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/oderfood?characterEncoding=utf-8&useSSL=false",
"root", "123456");
//定义sql语句,使用?表示占位符
String sql = "select * from product_info WHERE product_id = ?";
//获得预编译sql的对象
statement = connection.prepareStatement(sql);
//这只预编译对象的参数
statement.setString(1,"101");
//通过预编译对象执行查询并返回结果
set = statement.executeQuery();
while (set.next()){
System.out.println(set.getString(2)+"====="+set.getString(3));
}
} catch (Exception e) {
e.printStackTrace();
}finally {
//关闭连接等
if(set!=null){
try {
set.close();
} catch (SQLException e) {
e.printStackTrace();
}
} else if (statement!=null) {
try {
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
} else if (connection!=null) {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
}
主要分为一下几步
加载驱动 获得连接 通过连接获得sql预编译对象 为预编译sql中的占位符赋值 执行sql 解析结果 关闭连接
mybatis
初始优化
由于jdbc编程存在大量的硬编码,所以mybatis对其进行优化,将与数据库相关的配置信息放置在全局配置文件中,
<?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"></transactionManager>
<!--配置连接信息-->
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/oderfood?characterEncoding=utf-8&useSSL=false"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</dataSource>
</environment>
</environments>
<mappers> <!--这里配置的mapper文件-->
<mapper resource="mybatis/Product.xml"></mapper>
</mappers>
</configuration>
将对数据库的操作,即sql语句放在mapper文件中
<?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="test">
<!--由于库中列名和pojo属性名不一致,需要进行映射-->
<resultMap id="productInfoMap" type="com.jq.fram.pojo.ProductInfo">
<id column="product_id" property="productId"></id>
<result column="product_name" property="productName"></result>
<result column="product_price" property="productPrice"></result>
<result column="product_description" property="productDescription"></result>
<result column="product_stock" property="productStock"></result>
<result column="product_icon" property="productIcon"></result>
<result column="product_status" property="productStatus"></result>
<result column="category_type" property="categoryType"></result>
<result column="create_time" property="createTime"></result>
<result column="update_time" property="updateTime"></result>
</resultMap>
<!--#{id} 占位符-->
<select id="findById" resultMap="productInfoMap" parameterType="String">
SELECT * from product_info where product_id = #{id};
</select>
<!--'%${value}%' 拼接符,原样输出 简单类型时必须是value-->
<select id="findByIds" resultMap="productInfoMap" parameterType="String">
SELECT * from product_info where product_id like '%${value}%';
</select>
<insert id="add" parameterType="com.jq.fram.pojo.ProductInfo">
insert into product_info (product_id,product_name,product_price,product_stock,product_description,product_icon,product_status,category_type)
VALUES (#{productId},#{productName},#{productPrice},#{productStock},#{productDescription},#{productIcon},#{productStatus},#{categoryType});
</insert>
</mapper>
功能实现
package com.jq.fram.mybatis.mxl;
import com.jq.fram.pojo.ProductInfo;
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 org.junit.Test;
import org.springframework.beans.BeanUtils;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.List;
/**
* @author John
* @data 2018/3/17 11:10
*/
public class FindByXml {
public static void main(String[] args) throws Exception{
String source = "mybatis/config.xml";
InputStream inputStream = Resources.getResourceAsStream(source);
SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
SqlSession session = sessionFactory.openSession();
List<ProductInfo> user = session.selectList("test.findByIds", "1");
System.out.println(user);
session.close();
}
@Test
public void testAdd() throws IOException {
String source = "mybatis/config.xml";
InputStream stream = Resources.getResourceAsStream(source);
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(stream);
SqlSession sqlSession = factory.openSession();
ProductInfo one = sqlSession.selectOne("test.findById", "101");
//ProductInfo p2 = new ProductInfo();
/*p2.setProductId("100000");
p2.setProductName("jq");
p2.setCategoryType(8);
p2.setProductDescription("ok");
p2.setProductIcon("www.aaa.aa");
p2.setProductPrice(new BigDecimal(3.2));
p2.setProductStock(100);*/
one.setProductId("666");
sqlSession.insert("test.add",one);
sqlSession.commit();
sqlSession.close();
}
}
select mybatis自动提交,insert、update、delete都需要使用sqlSession.commit();手动提交。
传统dao方式
一个接口一个实现类,实现类中实现上述代码(创建session执行操作)
mapper接口
与上述方法一致
只是mapper文件中的namespace的值为接口的全限定名 id为方法名
并且当mapper文件放在src/main/java下时需要在pom文件中添加以下配置,不然找不到mapper.xml
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
</includes>
<filtering>false</filtering>
</resource>
</resources>
</build>
映射文件
输入映射
1、简单类型
<select id="findById" resultMap="productInfoMap" parameterType="String">
select * from product_info WHERE product_id = #{id};
</select>
id随意写的可以为任意值
2、pojo
<select id="findById" resultMap="productInfoMap" parameterType="com.xx.pojo">
select * from product_info WHERE product_id = #{id};
</select>
id为pojo的一个属性名
3、包装pojo
<select id="findById" resultMap="productInfoMap" parameterType="com.xx.pojoVO">
select * from product_info WHERE product_id = #{user.id};
</select>
public class pojovo {
private User user;
}
user时pojoVO类的一个成员变量
id时pojoVO成员变量user的一个属性
4、hashmap
<select id="findById" resultMap="productInfoMap" parameterType="hashmap">
select * from product_info WHERE product_id = #{xx};
</select>
xx为map的key值
输出映射
1、resultType
<select id="findById" resultType="productInfo" parameterType="String">
select * from product_info WHERE product_id = #{idsdadada};
</select>
但是只有当表的列名与pojo属性名一致才会有结果,(有一个一致结果不会为null但是不一致的属性值为null,都不一致时报空指针错误。)
2、resultMap
列名与属性名无要求,resultMap中进行关系映射。
<resultMap id="productInfoMap" type="com.jq.fram.pojo.ProductInfo">
<id column="product_id" property="productId"></id>
<result column="product_name" property="productName"></result>
<result column="product_price" property="productPrice"></result>
<result column="product_description" property="productDescription"></result>
<result column="product_stock" property="productStock"></result>
<result column="product_icon" property="productIcon"></result>
<result column="product_status" property="productStatus"></result>
<result column="category_type" property="categoryType"></result>
<result column="create_time" property="createTime"></result>
<result column="update_time" property="updateTime"></result>
</resultMap>
<select id="findById" resultMap="productInfoMap" parameterType="String">
select * from product_info WHERE product_id = #{idsdadada};
</select>
注意标红的要一致