mybatis基础知识2——mybatis入门程序4[修改和删除]

修改删除

      • 1.config配置文件包
        • ①.mybatis总的配置文件
        • ②.用来存放sql语句的配置文件User.xml
      • 2.src包
        • ①.实体类
        • ②.测试类

1.config配置文件包

①.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>
	<!-- 给数据库配置的环境 -->
	<!-- 与spring整合后,就没用了  -->
	<environments default="development">
		<environment id="development">
			<!-- JDBC事务管理器  -->
			<transactionManager type="JDBC"/>
			<!-- 连接池  -->
			<dataSource type="POOLED">
				<property name="driver" value="com.mysql.jdbc.Driver"/>
				<property name="url" value="jdbc:mysql://localhost:3306/mybase1"/>
				<property name="username" value="root"/>
				<property name="password" value="root123"/>
			</dataSource>
		</environment>
	</environments>
	
	<mappers>
		<!-- 用来加载自己写的一个xml配置文件  -->
		<!-- 配置文件中写的是sql语句  -->
		<mapper resource="User.xml"/>
	</mappers>
</configuration>

②.用来存放sql语句的配置文件User.xml

<?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">
	 <!-- 修改 -->
	 <update id="updateUser" parameterType="com.jp.pojo.User">
	 	update user1
	 	set username='${name}',sex=#{sex},address=#{address},birthday=#{birthday}
	 	where id=#{id};
	 </update>
	 <!-- 删除 -->
	 <delete id="deleteUser">
	 	delete from user1 where id=#{id};
	 </delete>
</mapper>

2.src包

①.实体类

User.java 参数id,name,sex,address,birthday,通过get,set方法

②.测试类

package com.jp.helloworld;

import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.List;

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.Before;
import org.junit.Test;

import com.jp.pojo.User;

public class Demo {
	
	private SqlSessionFactory sqlSessionFactory;
	
	//每次执行单元测试时都会先执行这个初始化代码
	@Before
	public void init() throws IOException{
		String resource="mybatis-config.xml";
		InputStream in=Resources.getResourceAsStream(resource);
		sqlSessionFactory = new SqlSessionFactoryBuilder().build(in);
	}
	@Test
	public void testUpdateUser(){
		SqlSession session = sqlSessionFactory.openSession();
		try{
			User user=new User();
			user.setId(5);
			user.setName("张无忌");
			user.setSex("男");
			user.setAddress("武当山");
			user.setBirthday(new Date());
			session.update("test.updateUser",user);
			session.commit();
		}finally{
			session.close();
		}
	}
	
	@Test
	public void testDeleteUser(){
		SqlSession session = sqlSessionFactory.openSession();
		try{
			session.selectList("test.deleteUser",5);
			session.commit();
		}finally{
			session.close();
		}
	}
}

你可能感兴趣的:(mybatis基础知识2——mybatis入门程序4[修改和删除])