添加客户
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
|
public class MyTest {
@Test public void test() throws IOException { SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
InputStream resourceAsStream = Resources.getResourceAsStream("SqlMappingConfig.xml");
SqlSessionFactory sessionFactory = sqlSessionFactoryBuilder.build(resourceAsStream);
SqlSession sqlSession = sessionFactory.openSession();
Customer customer = new Customer(); customer.setCust_name("疾风剑豪"); customer.setCust_profession("刺客"); customer.setCust_phone("13754784512"); customer.setEmail("303158131@qq.com"); sqlSession.insert("saveCustomer",customer);
sqlSession.commit();
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>
|