Myabtis的CRUD操作

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配置將廢除 -->
	<environments default="development">
		<environment id="development">
			<!-- 使用jdbc事務管理,事務控制由mybatis -->
			<transactionManager type="JDBC"/>
			<!-- 數據庫連接池,由mybatis控制 -->
			<dataSource type="POOLED">
				<property name="driver" value="com.mysql.jdbc.Driver"/>
				<property name="url" value="jdbc:mysql://localhost:3306/數據庫名稱"/>
				<property name="username" value="用戶名"/>
				<property name="password" value="密碼"/>
			</dataSource>
		</environment>
	</environments>
	
	<mappers>
		<mapper resource="mapper/User.xml"/>
	</mappers>
</configuration>
pojo類

package com.itachi.mybatis.bean;

import java.util.Date;

public class User {

	private int id;

	private String username;

	private String sex;

	private Date birthday;

	private String address;

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getSex() {
		return sex;
	}

	public void setSex(String sex) {
		this.sex = sex;
	}

	public Date getBirthday() {
		return birthday;
	}

	public void setBirthday(Date birthday) {
		this.birthday = birthday;
	}

	public String getAddress() {
		return address;
	}

	public void setAddress(String address) {
		this.address = address;
	}

	public User() {
		super();
		// TODO Auto-generated constructor stub
	}

	public User(int id, String username, String sex, Date birthday,
			String address) {
		super();
		this.id = id;
		this.username = username;
		this.sex = sex;
		this.birthday = birthday;
		this.address = address;
	}

	@Override
	public String toString() {
		return "User [id=" + id + ", username=" + username + ", sex=" + sex
				+ ", birthday=" + birthday + ", address=" + address + "]";
	}

}
映射文件:

<?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">
	<!-- 在映射文件中配置很多sql語句 -->
	<!-- 需求:通過id查詢用戶表的記錄 -->
	<!-- 通過select執行數據庫的查詢
		id:標識映射文件中的sql,將sql語句封裝到mappedStatement對象中,所以將id成爲statement的id
		parameterType:指定輸入參數的類型,這裏指定爲int
		#{}:表示一個佔位符
		#{id}:其中的id表示將接收的輸入參數,參數名稱就是id,如果輸入參數是簡單類型,#{}中的參數名可以隨意
		resultType:指定sql輸出結果的java對象類型,select指定resultType表示將單條記錄映射成java對象
	 -->
	<select id="findUserById" parameterType="int" resultType="com.itachi.mybatis.bean.User">
		SELECT * FROM USER WHERE id=#{id}
	</select>
	
	<!-- 根據用戶名稱模糊查詢用戶信息,可能返回多條記錄
	${}:表示拼接sql串,將接收到的參數內容不加任何修飾拼接在sql中 
	 -->
	<select id="findUserByName" parameterType="java.lang.String" resultType="com.itachi.mybatis.bean.User">
		SELECT * FROM USER WHERE username LIKE '%${value}%'
	</select>
	
	<!-- 添加用戶 -->
	<insert id="insertUser">
		INSERT INTO USER(username, birthday, sex, address) VALUES(#{username}, #{birthday}, #{sex}, #{address})
	</insert>
	
	<!-- 修改用戶 -->
	<update id="updateUser"  parameterType="com.itachi.mybatis.bean.User">
		UPDATE USER SET username=#{username}, birthday=#{birthday}, sex=#{sex}, address=#{address} WHERE id=#{id}
	</update>
	
	<!-- 刪除用戶 -->
	<delete id="deleteUser">
		DELETE FROM USER WHERE id=#{id}
	</delete>
	
</mapper>
CRUD操作:

package com.itachi.mybatis.test;

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.Test;

import com.itachi.mybatis.bean.User;

public class MybatisFirst {

	@Test 
	public void findUserByIdTest() throws IOException{
		//配置文件
		String resource  = "Mybatis-config.xml";
		//得到配置文件流
		InputStream is = Resources.getResourceAsStream(resource);
		//創建會話工廠,傳入配置文件信息
		SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
		//通過工廠得到sqlSession
		SqlSession sqlSession = sqlSessionFactory.openSession();
		//通過sqlSession操作數據庫
		//第一個參數:映射文件中statement的id,等於namespace+"."+statement的id
		//第二個參數:指定和映射文件中所匹配的parameterType類型的參數
		User user = sqlSession.selectOne("test.findUserById", 1);
		System.out.println(user);
		sqlSession.close();
	}
	
	@Test
	public void findUserByNameTest() throws IOException {
		String resource = "Mybatis-config.xml";
		InputStream is = Resources.getResourceAsStream(resource);
		SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
		SqlSession sqlSession = sqlSessionFactory.openSession();
		List<User> list = sqlSession.selectList("test.findUserByName", "小明");
		for (User user : list) {
			System.out.println(user);
		}
		sqlSession.close();
	}
	
	@Test
	public void insertUserTest() throws IOException {
		String resource = "Mybatis-config.xml";
		InputStream is = Resources.getResourceAsStream(resource);
		SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(is);
		SqlSession session = factory.openSession();
		int insert = session.insert("test.insertUser", new User(-1, "財子紫", "2", new Date(), "美國"));
		System.out.println(insert);
		session.commit();
		session.close();
	}
	
	@Test
	public void updateUserTest() throws IOException {
		String resource = "Mybatis-config.xml";
		InputStream is = Resources.getResourceAsStream(resource);
		SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(is);
		SqlSession session = factory.openSession();
		int update = session.update("test.updateUser", new User(27, "宏宇族", "2", new Date(), "新加坡"));
		System.out.println(update);
		session.commit();
		session.close();
	}
	
	@Test
	public void deleteUserTest() throws IOException {
		String resource = "Mybatis-config.xml";
		InputStream is = Resources.getResourceAsStream(resource);
		SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(is);
		SqlSession session = factory.openSession();
		int delete = session.update("test.deleteUser", 27);
		System.out.println(delete);
		session.commit();
		session.close();
	}
	
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章