0%

MyBaits保存更新删除

添加客户

1
2
3
4
5
6
<!--保存用户-->
<insert id="saveCustomer" parameterType="com.qc.domain.Customer">
INSERT INTO `customer`
(cust_name,cust_profession,cust_phone,email) VALUES
(#{cust_name},#{cust_profession},#{cust_phone},#{email})
</insert>

测试类调用,需要手动提交事务,sqlSession 调用的方法名,以及参数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
/**
* @author 30315
* @title: MyTest
* @projectName MyBatisPro-01
* @description: TODO
* @date 2020-03-0112:24
*/
public class MyTest {

@Test
public void test() throws IOException {
// 1.SqlSessionFactoryBuilder 加载配置文件
SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();

// 2.读取配置文件
InputStream resourceAsStream = Resources.getResourceAsStream("SqlMappingConfig.xml");

// 3.获取Session工厂
SqlSessionFactory sessionFactory = sqlSessionFactoryBuilder.build(resourceAsStream);

// 4.获取回话 --- JDBC连接
SqlSession sqlSession = sessionFactory.openSession();

// 5.执行SQL
Customer customer = new Customer();
customer.setCust_name("疾风剑豪");
customer.setCust_profession("刺客");
customer.setCust_phone("13754784512");
customer.setEmail("303158131@qq.com");
sqlSession.insert("saveCustomer",customer);

// 6.提交事务
sqlSession.commit();

// 7.释放资源
sqlSession.close();
}

}

返回添加过后自增的主键

1
2
3
4
5
6
7
8
9
10
<!--保存用户-->
<insert id="saveCustomer" parameterType="com.qc.domain.Customer">
<selectKey keyColumn="cust_id" keyProperty="cust_id" order="AFTER" resultType="Long">
SELECT LAST_INSERT_ID()
</selectKey>

INSERT INTO `customer`
(cust_name,cust_profession,cust_phone,email) VALUES
(#{cust_name},#{cust_profession},#{cust_phone},#{email})
</insert>

执行完插入语句后,打印添加之前对象的 ID,resultType 的类型要和 domain 的类型一致

1
System.out.println(customer.getCust_id());

更新客户

1
2
3
4
5
<!--更新客户-->
<update id="updateCustomerById" parameterType="com.qc.domain.Customer">
UPDATE `customer` SET
cust_name = #{cust_name} WHERE cust_id = #{cust_id}
</update>

删除客户

1
2
3
4
<delete id="deleteCustomerById" parameterType="Long">
DELETE FROM `customer` WHERE
cust_id = #{cust_id}
</delete>
↓赏一个鸡腿... 要不,半个也行↓