添加客户
<!--保存用户--> <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 调用的方法名,以及参数
/** * @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(); } }
返回添加过后自增的主键
<!--保存用户--> <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 的类型一致
System.out.println(customer.getCust_id());
更新客户
<!--更新客户--> <update id="updateCustomerById" parameterType="com.qc.domain.Customer"> UPDATE `customer` SET cust_name = #{cust_name} WHERE cust_id = #{cust_id} </update>
删除客户
<delete id="deleteCustomerById" parameterType="Long"> DELETE FROM `customer` WHERE cust_id = #{cust_id} </delete>