Mybatis使用SqlSession进行CRUD

package com.jdbc.demo;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class UseJDBC {

	public static void main(String[] args){
		
		try {
			Class.forName("oracle.jdbc.driver.OracleDriver");
			Connection conn = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:orcl", "system", "bruce123");
			String sql = "select * from student where id = ?";
			PreparedStatement ps = conn.prepareStatement(sql);
			ps.setInt(1, 1);
			ResultSet rs = ps.executeQuery();
			while(rs.next()){
				System.out.println(rs.getString("id") + "-" + rs.getString("name"));
			}
		} catch (ClassNotFoundException | SQLException e) {
			e.printStackTrace();
		}
	}
}
package com.mybatis.demo;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
import com.mybatis.domain.Student;
import com.mybatis.utils.SessionFactoryUtil;

public class StudentMybatis {

	@Test
	public void queryStudent(){
		SqlSession sqlSession =  SessionFactoryUtil.getSessionFactory().openSession(true);
		Student s = sqlSession.selectOne("student.selectbyid", 5);
		System.out.println(s);
		sqlSession.close();
	}
	
	@Test
	public void queryStudentsByIds(){
		SqlSession sqlSession =  SessionFactoryUtil.getSessionFactory().openSession(true);
		//Integer[] ids = new Integer[]{1,2,3,4,5};
		Map<String,Object> map = new HashMap<String, Object>();
		map.put("ids", new Integer[]{1,2,3,4,5});
		List<Integer> list = new ArrayList<Integer>();
		list.add(1);
		list.add(2);
		list.add(3);
		//map.put("ids", list);
		List<Object> students  = sqlSession.selectList("student.queryStudentsByIds", map);
		for(Object s : students){
			System.out.println(s);
		}
		sqlSession.close();
	}
	
	@Test
	public void queryStus(){
		SqlSession sqlSession =  SessionFactoryUtil.getSessionFactory().openSession(true);
		//List<Object> students = sqlSession.selectList("student.querybyname", "李小明");
		List<Object> students = sqlSession.selectList("student.querybyname", "%小明%");
		for(Object s : students){
			System.out.println(s);
		}
		sqlSession.close();
	}
	
	@Test
	public void queryStus2(){
		SqlSession sqlSession =  SessionFactoryUtil.getSessionFactory().openSession(true);
		List<Object> students = sqlSession.selectList("student.querybyname2", "小明");
		for(Object s : students){
			System.out.println(s);
		}
		sqlSession.close();
	}
	
	@Test
	public void queryStus3(){
		SqlSession sqlSession =  SessionFactoryUtil.getSessionFactory().openSession(true);
		Student s = new Student();
		//s.setId(12);
		s.setName("%小明%");
		//s.setBirthday(new Date());
		//s.setSex("F");
		//s.setAddress("北京市");
		List<Object> students = sqlSession.selectList("student.querybyStudent", s);
		for(Object o : students){
			System.out.println(o);
		}
		sqlSession.close();
	}
	
	@Test
	public void addStudent(){
		SqlSession sqlSession =  SessionFactoryUtil.getSessionFactory().openSession(true);
		Student s = new Student();
		s.setId(12);
		s.setName("tom");
		//s.setBirthday(new Date());
		s.setSex("F");
		//s.setAddress("北京市");
		int code = sqlSession.insert("student.addStudent",s);
		System.out.println(code);
		sqlSession.close();
	}
	
	@Test
	public void updateStudent(){
		SqlSession sqlSession =  SessionFactoryUtil.getSessionFactory().openSession(true);
		Student s = new Student();
		s.setId(10);
		s.setName("jack");
		//s.setBirthday(new Date());
		//s.setSex("F");
		s.setAddress("北京市西城区");
		int code = sqlSession.update("student.updateStudent",s);
		System.out.println(code);
		sqlSession.close();
	}
	
	@Test
	public void deleteStudent(){
		SqlSession sqlSession =  SessionFactoryUtil.getSessionFactory().openSession(true);
		int code = sqlSession.delete("student.deleteStudent",2);
		System.out.println(code);
		sqlSession.close();
	}
}
package com.mybatis.domain;

import java.util.Date;

public class Student {

	private Integer id;
	private String name;
	private Date birthday;
	private String sex;
	private String address;
	
	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public Date getBirthday() {
		return birthday;
	}
	public void setBirthday(Date birthday) {
		this.birthday = birthday;
	}
	public String getSex() {
		return sex;
	}
	public void setSex(String sex) {
		this.sex = sex;
	}
	public String getAddress() {
		return address;
	}
	public void setAddress(String address) {
		this.address = address;
	}
	@Override
	public String toString() {
		return "Student [id=" + id + ", name=" + name + ", birthday="
				+ birthday + ", sex=" + sex + ", address=" + address + "]";
	}
	
}
package com.mybatis.utils;

import java.io.IOException;
import java.io.InputStream;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

public class SessionFactoryUtil {

	public static SqlSessionFactory getSessionFactory(){
		SqlSessionFactory sqlSessionFactory = null;
		try {
			// 1.加载核心配置文件
			InputStream inputStream  = Resources.getResourceAsStream("mybatis-config.xml");
			// 2.读取配置文件的内容
			SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
			sqlSessionFactory = builder.build(inputStream);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return sqlSessionFactory;
	}
}
<?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="student">
<select id="selectbyid" parameterType="int" resultType="com.mybatis.domain.Student">
select * from student where id = #{id}
</select>

<select id="queryStudentsByIds" resultType="com.mybatis.domain.Student" parameterType="java.util.Map">
<!-- select * from student where id in #{ids} fail-->
<!-- select * from student where id in ${ids} fail-->
select * from student where id in 
    <foreach collection="ids" item="id" open="(" close=")" separator=",">
       #{id}
   </foreach> 
</select>

<select id="querybyname" parameterType="string" resultType="com.mybatis.domain.Student">
select * from student where name like #{name}
</select>

<select id="querybyname2" parameterType="string" resultType="com.mybatis.domain.Student">
select * from student where name like '%${value}%'
</select>

<select id="querybyStudent" parameterType="com.mybatis.domain.Student" resultType="com.mybatis.domain.Student">
select * from student where 1=1 
<if test= "id != null and id !=''">and id = #{id} </if>
<if test= "name != null and name !=''">and name like #{name} </if>
<if test= "sex != null and sex !=''">and sex = #{sex} </if>
</select>

<insert id="addStudent" parameterType="com.mybatis.domain.Student"> 
<!-- insert into student (id,name,birthday,sex,address) values (#{id},#{name},#{birthday},#{sex},#{address})-->
insert into student 
<trim prefix= "(" suffix= ")" suffixOverrides= ",">
	<if test= "id != null">id,</if>
	<if test= "name != null">name,</if>
	<if test= "birthday != null">birthday,</if>
	<if test= "sex != null">sex,</if>
	<if test= "address != null">address,</if>
</trim>
<trim prefix= "values (" suffix= ")" suffixOverrides= ",">
	<if test= "id != null">#{id},</if>
	<if test= "name != null">#{name},</if>
	<if test= "birthday != null">#{birthday},</if>
	<if test= "sex != null">#{sex},</if>
	<if test= "address != null">#{address},</if>
</trim>
</insert>

<update id="updateStudent" parameterType="com.mybatis.domain.Student">
<!--  update student set name =#{name}, birthday=#{birthday},sex=#{sex},address=#{address} where id = #{id} -->
update student 
 <trim prefix="set" suffixOverrides=",">
     <if test="name != null">name=#{name},</if>
     <if test="birthday != null">birthday=#{birthday},</if>
     <if test="sex != null">sex=#{sex},</if>
     <if test="address != null">address=#{address},</if>
 </trim>
where id = #{id}           
</update>

<delete id="deleteStudent" parameterType="int">
delete from student where id = #{id}
</delete>

</mapper>
log4j.rootLogger=DEBUG,stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} [%l] [%p]:%m%n
<?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>
	<!-- 运行环境配置 -->
	<!--default属性:指定使用哪一个运行环境  -->
	<environments default="development">
		<!--id属性:唯一标识一个运行环境  -->
		<environment id="development">
			<!-- 事务管理器配置,type="JDBC":mybatis框架默认使用jdbc事务 -->
			<transactionManager type="JDBC" />
			<!--数据源配置,type="POOLED":mybatis框架提供的连接池  -->
			<dataSource type="POOLED">
				<property name="driver" value="oracle.jdbc.driver.OracleDriver" />
				<property name="url" value="jdbc:oracle:thin:@localhost:1521:orcl" />
				<property name="username" value="system" />
				<property name="password" value="bruce123" />
			</dataSource>
		</environment>
	</environments>
	<!-- 加载映射文件 -->
	<mappers>
		<mapper resource="com/mybatis/xmlmapper/StudentMapper.xml"/>
	</mappers>
</configuration>
发布了132 篇原创文章 · 获赞 64 · 访问量 47万+

猜你喜欢

转载自blog.csdn.net/qiuzhi__ke/article/details/104151427