mybatis框架知识点:sql根据id删除员工操作
package mybatis311_02_delete;
import java.io.IOException;
import java.io.InputStream;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
public class DeleteTest {
public static void main(String[] args) throws IOException {
//模拟删除操作
1.创建输入流对象
InputStream is=Resources.getResourceAsStream("mybatis-config.xml");
2.创建会话工厂
SqlSessionFactory sessionFactory=new SqlSessionFactoryBuilder().build(is);
3.创建会话
SqlSession sqlSession=sessionFactory.openSession();
4.调用删除方法,deleteEmpById 一条deletesql语句的id
int rows=sqlSession.delete("emp.deleteEmpById", 111);
sqlSession.commit();
5.关闭session会话
sqlSession.close();
}
}
mybatis主配置文件mybatis-config.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="armbank">
<environment id="armbank">
<transactionManager type="JDBC"></transactionManager>
<dataSource type="pooled">
<property name="url" value="jdbc:oracle:thin:@localhost:1521:orcl"/>
<property name="username" value="scott"/>
<property name="driver" value="oracle.jdbc.driver.OracleDriver"/>
<property name="password" value="tiger"/>
</dataSource>
</environment>
</environments>
<mappers>
<!-- 映射文件写好之后一定要告诉主配置文件,否则报错 -->
<mapper resource="EmpMapper.xml"/>
</mappers>
</configuration>
映射文件EmpMapper.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="emp">
<delete id="deleteEmpById" parameterType="Integer">
delete from emp where empno=#{id}
</delete>
</mapper>