@[toc]
目的
- 学会编写的 CRUD
完成内容
- 编写一个 MyBatis 的程序 ,对客户表进行 CRUD 操作,然后查询出指定条件的客户表内容
- 编写一个 MyBatis 的程序 ,使用代理方式,对客户表进行 CR 操作
- 编写一个 MyBatis 的程序 ,使用注解的方式,对商品表进行 UD 操作
mybatis基本配置
SqlMapConfig.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>
<!--配置环境-->
<environments default="mysql">
<environment id="mysql">
<transactionManager type="JDBC">
</transactionManager>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.cj.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://127.0.0.1:3306/java_mybatis?serverTimezone=UTC"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</dataSource>
</environment>
</environments>
<!--引入配置文件-->
<mappers>
<!-- <package name="com.yang.mapper"/>-->
<mapper resource="com/yang/mapper/GoodsMapper.xml" />
<mapper resource="com/yang/mapper/CustomerMapper.xml" />
</mappers>
</configuration>
log4j.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration>
<!-- 将日志信息输出到控制台 -->
<appender name="ConsoleAppender" class="org.apache.log4j.ConsoleAppender">
<!-- 设置日志输出的样式 -->
<layout class="org.apache.log4j.PatternLayout">
<!-- 设置日志输出的格式 -->
<param name="ConversionPattern" value="[%d{yyyy-MM-dd HH:mm:ss:SSS}] [%-5p] [method:%l]%n%m%n%n" />
</layout>
<!--过滤器设置输出的级别-->
<filter class="org.apache.log4j.varia.LevelRangeFilter">
<!-- 设置日志输出的最小级别 -->
<param name="levelMin" value="WARN" />
<!-- 设置日志输出的最大级别 -->
<param name="levelMax" value="ERROR" />
<!-- 设置日志输出的xxx,默认是false -->
<param name="AcceptOnMatch" value="true" />
</filter>
</appender>
<!-- 将日志信息输出到文件,但是当文件的大小达到某个阈值的时候,日志文件会自动回滚 -->
<appender name="RollingFileAppender" class="org.apache.log4j.RollingFileAppender">
<!-- 设置日志信息输出文件全路径名 -->
<param name="File" value="D:/log4j/RollingFileAppender.log" />
<!-- 设置是否在重新启动服务时,在原有日志的基础添加新日志 -->
<param name="Append" value="true" />
<!-- 设置保存备份回滚日志的最大个数 -->
<param name="MaxBackupIndex" value="10" />
<!-- 设置当日志文件达到此阈值的时候自动回滚,单位可以是KB,MB,GB,默认单位是KB -->
<param name="MaxFileSize" value="10KB" />
<!-- 设置日志输出的样式 -->
<layout class="org.apache.log4j.PatternLayout">
<!-- 设置日志输出的格式 -->
<param name="ConversionPattern" value="[%d{yyyy-MM-dd HH:mm:ss:SSS}] [%-5p] [method:%l]%n%m%n%n" />
</layout>
</appender>
<!-- 将日志信息输出到文件,可以配置多久产生一个新的日志信息文件 -->
<appender name="DailyRollingFileAppender" class="org.apache.log4j.DailyRollingFileAppender">
<!-- 设置日志信息输出文件全路径名 -->
<param name="File" value="D:/log4j/DailyRollingFileAppender.log" />
<!-- 设置日志每分钟回滚一次,即产生一个新的日志文件 -->
<param name="DatePattern" value="'.'yyyy-MM-dd-HH-mm'.log'" />
<!-- 设置日志输出的样式 -->
<layout class="org.apache.log4j.PatternLayout">
<!-- 设置日志输出的格式 -->
<param name="ConversionPattern" value="[%d{yyyy-MM-dd HH:mm:ss:SSS}] [%-5p] [method:%l]%n%m%n%n" />
</layout>
</appender>
<!--
注意:
1:当additivity="false"时,root中的配置就失灵了,不遵循缺省的继承机制
2:logger中的name非常重要,它代表记录器的包的形式,有一定的包含关系,试验表明
2-1:当定义的logger的name同名时,只有最后的那一个才能正确的打印日志
2-2:当对应的logger含有包含关系时,比如:name=test.log4j.test8 和 name=test.log4j.test8.UseLog4j,则2-1的情况是一样的
2-3:logger的name表示所有的包含在此名的所有记录器都遵循同样的配置,name的值中的包含关系是指记录器的名称哟!注意啦!
3:logger中定义的level和appender中的filter定义的level的区间取交集
4:如果appender中的filter定义的 levelMin > levelMax ,则打印不出日志信息
-->
<!-- 指定logger的设置,additivity指示是否遵循缺省的继承机制-->
<logger name="test.log4j.test8.UseLog4j" additivity="false">
<level value ="WARN"/>
<appender-ref ref="DailyRollingFileAppender"/>
</logger>
<!--指定logger的设置,additivity指示是否遵循缺省的继承机制 -->
<logger name="test.log4j.test8.UseLog4j_" additivity="false">
<level value ="ERROR"/>
<appender-ref ref="RollingFileAppender"/>
</logger>
<!-- 根logger的设置-->
<root>
<level value ="INFO"/>
<appender-ref ref="ConsoleAppender"/>
<appender-ref ref="DailyRollingFileAppender"/>
</root>
</log4j:configuration>
编写一个 MyBatis 的程序 ,对客户表进行 CRUD 操作,然后查询出指定条件的客户表内容
mapper文件
CustomerMapper.xml
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <!-- 为这个 mapper 指定一个唯一的 namespace, namespace 的值习惯上设置成包名+sql 映射文件名, 这样就能够保证 namespace 的值是唯一的 -->
<mapper namespace="com.yang.mapper.CustomerMapper"> <!-- #{}占位符 -->
<select id="getCustomers" parameterType="int" resultType="com.yang.pojo.Customer">
select *
from customer
where id = #{id}
</select>
<select id="getCustomersByLike" parameterType="java.lang.String" resultType="com.yang.pojo.Customer"> select *
from customer
where name like '%${value}%' </select>
<insert id="insertCustomer" parameterType="com.yang.pojo.Customer">
<selectKey keyProperty="id" order="AFTER" resultType="java.lang.Integer">select last_insert_id()</selectKey>
insert into customer(id,name,level) values(#{id},#{name},#{level})
</insert>
<update id="updateCustomer" parameterType="com.yang.pojo.Customer"> update customer
set name = #{name},
level = #{level}
where id = #{id} </update>
<delete id="deleteCustomer" parameterType="int"> delete from customer where id = #{id} </delete>
</mapper>
GoodsMapper.xml
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <!-- 为这个 mapper 指定一个唯一的 namespace, namespace 的值习惯上设置成包名+sql 映射文件名, 这样就能够保证 namespace 的值是唯一的 -->
<mapper namespace="com.yang.mapper.GoodsMapper"> <!-- #{}占位符 -->
<select id="getGoods" parameterType="int" resultType="com.yang.pojo.Goods">
select *
from gds_goods
where gds_id = #{gds_id}
</select>
<select id="getGoodsByLike" parameterType="java.lang.String" resultType="com.yang.pojo.Goods"> select *
from gds_goods
where gds_name like '%${value}%' </select>
<insert id="insertGoods" parameterType="com.yang.pojo.Goods">
<selectKey keyProperty="gds_id" order="AFTER" resultType="java.lang.Integer">select last_insert_id()</selectKey>
insert into gds_goods(gds_id,gds_no, gds_name, gds_price,gds_path,gds_memo) values(#{gds_id},#{gds_no},
#{gds_name}, #{gds_price}, #{gds_path}, #{gds_memo})
</insert>
<update id="updateGoods" parameterType="com.yang.pojo.Goods"> update gds_goods
set gds_path = #{gds_path},
gds_memo = #{gds_memo}
where gds_id = #{gds_id} </update>
<delete id="deleteGoods" parameterType="int"> delete from gds_goods where gds_id = #{gds_id} </delete>
</mapper>
实体类pojo
Customer.java
package com.yang.pojo;
public class Customer {
private Integer id;
private String name;
private String level;
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 String getLevel() {
return level;
}
public void setLevel(String level) {
this.level = level;
}
public Customer() {
}
@Override
public String toString() {
return "Customer{" +
"id=" + id +
", name='" + name + '\'' +
", level='" + level + '\'' +
'}';
}
}
Goods.java
package com.yang.pojo;
public class Goods {
private int gds_id;
private String gds_no;
private String gds_name;
private Double gds_price;
private String gds_path;
private String gds_memo;
public int getGds_id() {
return gds_id;
}
public void setGds_id(int gds_id) {
this.gds_id = gds_id;
}
public String getGds_no() {
return gds_no;
}
public void setGds_no(String gds_no) {
this.gds_no = gds_no;
}
public String getGds_name() {
return gds_name;
}
public void setGds_name(String gds_name) {
this.gds_name = gds_name;
}
public Double getGds_price() {
return gds_price;
}
public void setGds_price(Double gds_price) {
this.gds_price = gds_price;
}
public String getGds_path() {
return gds_path;
}
public void setGds_path(String gds_path) {
this.gds_path = gds_path;
}
public String getGds_memo() {
return gds_memo;
}
public void setGds_memo(String gds_memo) {
this.gds_memo = gds_memo;
}
@Override
public String toString() {
return "Goods [gds_id=" + gds_id + ", gds_no=" + gds_no + ", gds_name=" + gds_name + ", gds_price=" + gds_price + ", gds_path=" + gds_path + ", gds_memo=" + gds_memo + "]";
}
}
测试类
实现模糊查找
@Test
public void testSearchCustomer() throws IOException {
SqlSession ss = ssf.openSession();
String statement = "com.yang.mapper.CustomerMapper.getCustomersByLike";
List<Customer> customers = ss.selectList(statement, "吴彦祖");
System.out.println(customers);
ss.close();
}
查找关键字吴彦祖,显示吴彦祖以及南京吴彦祖分祖的信息
实现增加数据操作
@Test
public void testInsertCustomer() throws IOException {
SqlSession ss = ssf.openSession();
String statement = "com.yang.mapper.CustomerMapper.insertCustomer";
Customer customers = new Customer();
customers.setId(5);
customers.setName("暴力阿扬");
customers.setLevel("s1");
ss.insert(statement, customers);
System.out.println(customers.getId());
ss.commit();
ss.close();
}
控制台打印0,插入成功
刷新数据库
实现修改数据操作
@Test
public void testUpdateCustomer() throws IOException {
SqlSession ss = ssf.openSession();
String getCustomers = "com.yang.mapper.CustomerMapper.getCustomers";
Customer cus = ss.selectOne(getCustomers, 3);
cus.setName("你扬哥");
cus.setLevel("s8");
String statement = "com.yang.mapper.CustomerMapper.updateCustomer";
int rel = ss.update(statement, cus);
System.out.println(rel);
ss.commit();
ss.close();
}
成功修改
实现删除操作
@Test
public void testDeleteCustomer() throws IOException {
SqlSession ss = ssf.openSession();
String statement = "com.yang.mapper.CustomerMapper.deleteCustomer";
int rel = ss.update(statement, 3);
ss.commit();
System.out.println(rel);
ss.close();
}
已被删除
编写一个 MyBatis 的程序 ,使用代理方式,对客户表进行 CR 操作
在mybatis根配置的mappers中加入
<mapper class="com.yang.dao.CustomerMapper" />
编写dao层
package com.yang.mapper;
import com.yang.pojo.Customer;
import java.util.List;
public interface CustomerMapper {
public Customer getCustomers(int id);
public List<Customer> getCustomersByLike(String condition);
public int insertCustomer(Customer customer);
}
进行测试
@Test
public void testGetCustomersByLikeProxy() throws IOException {
SqlSession ss = ssf.openSession();
String statement = "com.yang.mapper.CustomerMapper.getCustomersByLike";
List<Customer> customers = ss.selectList(statement, "暴力阿扬");
System.out.println(customers);
ss.close();
}
测试成功
测试增添操作
@Test
public void testInsertCustomerProxy() throws IOException {
SqlSession ss = ssf.openSession();
Customer customer = new Customer();
customer.setLevel("s1");
customer.setId(66);
customer.setName("ViolentAyang");
CustomerMapper customerMapper = ss.getMapper(CustomerMapper.class);
customerMapper.insertCustomer(customer);
System.out.println(customer.getId());
ss.commit();
ss.close();
}
编写一个 MyBatis 的程序 ,使用注解的方式,对商品表进行 UD 操作
编写dao层
package com.yang.mapper;
import com.yang.pojo.Goods;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
public interface GoodsMapper {
@Update("update gds_goods set gds_path = #{gds_path}, gds_memo = #{gds_memo} where gds_id = #{gds_id}")
public int UpdateGoods(Goods goods);
@Delete("delete from gds_goods where gds_id = #{gds_id}")
public int DeleteGoods(int gds_id);
}
编写测试类
@Test
public void testUpdateGoods() throws IOException {
SqlSession ss = ssf.openSession();
Goods gds = new Goods();
gds.setGds_id(0);
gds.setGds_memo("测试修改备注");
gds.setGds_path("测试修改路径");
GoodsMapper gdsMapper = ss.getMapper(GoodsMapper.class);
gdsMapper.UpdateGoods(gds);
ss.commit();
ss.close();
}
修改成功
测试删除操作
@Test
public void TestDeleteGoods() throws IOException {
SqlSession ss = ssf.openSession();
GoodsMapper gdsMapper = ss.getMapper(GoodsMapper.class);
gdsMapper.DeleteGoods(0);
ss.commit();
ss.close();
}
删除成功