03.Mybatis框架的第一次使用

03.Mybatis框架的第一次使用

项目结构图:

03.Mybatis框架的第一次使用_第1张图片

1、Po类(数据库表对应的java模型)

UserPo.java

package com.company.project.model;

/**
 * @author God_86
 *
 */
public class UserPo {
	private long userId;
	private String userName;
	private long phoneNum;
	private String password;
	private String name;
	private String sex;
	private String shippingAddress;
	
	public UserPo() {
		super();
		this.userId = 0;
		this.userName = "";
		this.phoneNum = 0;
		this.password = "";
		this.name = "";
		this.sex = "";
		this.shippingAddress = "";
	}



	public String getUserName() {
		return userName;
	}

	public long getPhoneNum() {
		return phoneNum;
	}

	public String getPassword() {
		return password;
	}

	public String getName() {
		return name;
	}

	public String getSex() {
		return sex;
	}

	public String getShippingAddress() {
		return shippingAddress;
	}

	public long getUserId() {
		return userId;
	}

	public void setUserId(long userId) {
		this.userId = userId;
	}

	public void setUserName(String userName) {
		this.userName = userName;
	}

	public void setPhoneNum(long phoneNum) {
		this.phoneNum = phoneNum;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public void setName(String name) {
		this.name = name;
	}

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

	public void setShippingAddress(String shippingAddress) {
		this.shippingAddress = shippingAddress;
	}

	@Override
	public String toString() {
		return "UserPo [userId=" + userId + ", userName=" + userName + ", phoneNum=" + phoneNum + ", password="
				+ password + ", name=" + name + ", sex=" + sex + ", shippingAddress=" + shippingAddress + "]";
	}



	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + ((name == null) ? 0 : name.hashCode());
		result = prime * result + ((password == null) ? 0 : password.hashCode());
		result = prime * result + (int) (phoneNum ^ (phoneNum >>> 32));
		result = prime * result + ((sex == null) ? 0 : sex.hashCode());
		result = prime * result + ((shippingAddress == null) ? 0 : shippingAddress.hashCode());
		result = prime * result + (int) (userId ^ (userId >>> 32));
		result = prime * result + ((userName == null) ? 0 : userName.hashCode());
		return result;
	}


	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		UserPo other = (UserPo) obj;
		if (name == null) {
			if (other.name != null)
				return false;
		} else if (!name.equals(other.name))
			return false;
		if (password == null) {
			if (other.password != null)
				return false;
		} else if (!password.equals(other.password))
			return false;
		if (phoneNum != other.phoneNum)
			return false;
		if (sex == null) {
			if (other.sex != null)
				return false;
		} else if (!sex.equals(other.sex))
			return false;
		if (shippingAddress == null) {
			if (other.shippingAddress != null)
				return false;
		} else if (!shippingAddress.equals(other.shippingAddress))
			return false;
		if (userId != other.userId)
			return false;
		if (userName == null) {
			if (other.userName != null)
				return false;
		} else if (!userName.equals(other.userName))
			return false;
		return true;
	}	
}

2、mapper接口类(数据库表操作的方法接口)

UserMapper.java

package com.company.project.mapper;

import java.util.List;

import org.apache.ibatis.annotations.Select;

import com.company.project.model.UserPo;

public interface UserMapper {
	//插入方法
	boolean insert(UserPo userPo);
	
	//更新方法
	boolean update(UserPo userPo);
	
	//删除方法
	boolean delete(long id);
	
	//查询主键
	UserPo findById(long id);
	
	//查询所有
	List<UserPo> findAll();

3、配置文件的编写(java Po 类与数据库表操作的对应关系)

UserMapper.xml



<mapper namespace="com.company.project.mapper.UserMapper">


	
	<resultMap type="userpo" id="baseResultSet">
	
		<id  column="id" property="userId"/>
		<result column="user_name" property="userName" />
		<result column="phone_num" property="phoneNum" />
		<result column="password" property="password"  />
		<result column="name" property="name"  />
		<result column="sex" property="sex"  />
		<result column="shipping_address" property="shippingAddress"  />	
	resultMap>
	
	
	
	<select id="findById"  resultMap="baseResultSet">
		select id , user_name , phone_num , password , name ,sex,shipping_address from  "USER"
		where id=#{id}
		
		 
	select>
	
	
	<select id="findAll"  resultMap="baseResultSet">
		select id , user_name , phone_num , password , name ,sex,shipping_address from  "USER"
	select>
	
	
	<insert id="insert" parameterType="UserPo" >
		insert into "USER" values(
			#{userId},
			#{userName},
			#{phoneNum},
			#{password},
			#{name},
			#{sex},
			#{shippingAddress}
		)
	insert>
	
	
	<update id="update" parameterType="UserPo">
		update "USER"  set  
			user_name=#{userName},
			phone_num=#{phoneNum},
			password=#{password},
			name=#{name},
			sex=#{sex},
			shipping_address=#{shippingAddress}	
		Where  id = #{userId}
	update>
	
		
	<delete id="delete" parameterType="java.lang.Long">
		delete "USER" 
		Where  id = #{userId}
	delete>
mapper>

4、更新主配文件

mybatis-config.xml 文件



<configuration>
	
	<properties resource="jdbc.properties">properties>
	<typeAliases>
	
	<package name="com.company.project.model"/>
	typeAliases>
	
	
	<environments default="development">
		<environment id="development">
			<transactionManager type="JDBC" />
			<dataSource type="POOLED">
				
				
				<property name="username" value="${username}" />
				<property name="password" value="${password}" />
			dataSource>
		environment>
	environments>
	

	
	<mappers>
		
		<package name="com.company.project.mapper" />
	mappers>
configuration>

(1)在 < typeAliases >标签中,利用< package > 导入所有的model Po类

(2)在 < mappers >标签中,利用< package > 导入所有的 XXXMapper.xml配置文件。

注意:

  • 接口类应该和对应的配置类同名,这样才可以自动配置,可以省去很多步骤
  • 接口类XXXMapper.java应该和对应的配置类XXXMapper.xml应该写在同一个包下,这样可以自动配置。
  • 但是为了防止臃肿,我们可以把配置类XXXMapper.xml文件写在conf下,创建一个与接口类XXXMapper.java同名的包,把XXXMapper.xml文件写在包下,这样看起来,他们两个文件就没有在同一目录下,但是编译以后,在build路径下,接口类XXXMapper.java编译生成的XXXMapper.class会和XXXMapper.xml编译生成的XXXMapper.xml在同一目录文件下,所以间接性的把两个文件放在了同一包下,实现了上述的要求。

5、测试

UserMapperTest.java

package com.company.project.daotest;

import java.util.List;

import org.apache.ibatis.session.SqlSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.company.project.mapper.UserMapper;
import com.company.project.model.UserPo;
import com.company.project.util.MyBatisUtil;


import junit.framework.TestCase;

public class UserMapperTest extends TestCase{
	
	public void testFindById() {
		Logger logger = LoggerFactory.getLogger("hello");
		//获取会话
		SqlSession session = MyBatisUtil.getSession();
		try {
			//获取接口的实现类对象
			//会自动为接口创建一个代理对象,代理对象去执行增删改查
			UserMapper mapper = session.getMapper(UserMapper.class);
			UserPo userPo = mapper.findById(1000001l);
			System.out.println(userPo);
			logger.info(userPo.toString());
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			session.close();
		}
	}
	
	public void testFindAll() {
		
		//获取会话
		SqlSession session = MyBatisUtil.getSession();
		try {
			//获取接口的实现类对象
			//会自动为接口创建一个代理对象,代理对象去执行增删改查
			UserMapper mapper = session.getMapper(UserMapper.class);
			List<UserPo> userPoList = mapper.findAll();
			for(UserPo userPo : userPoList) {
				System.out.println(userPo.toString());
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			session.close();
		}
	}
	
	public void testInsert() {
		//获取会话
		SqlSession session = MyBatisUtil.getSession();
		try {
			//获取接口的实现类对象
			//会自动为接口创建一个代理对象,代理对象去执行增删改查
			UserMapper mapper = session.getMapper(UserMapper.class);
			UserPo userPo = new UserPo();
			userPo.setUserId(1000003l);
			userPo.setName("王五");
			userPo.setPassword("123456");
			userPo.setPhoneNum(15555555555l);
			userPo.setSex("女");
			userPo.setShippingAddress("陕西省");
			userPo.setUserName("小仙女");
			System.out.println(userPo.toString());
			boolean flag = mapper.insert(userPo);
			if(flag) {
				session.commit();
				System.out.println("插入成功");
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			session.close();
		}
	}
	
	public void testUpdate() {
		//获取会话
		SqlSession session = MyBatisUtil.getSession();
		try {
			//获取接口的实现类对象
			//会自动为接口创建一个代理对象,代理对象去执行增删改查
			UserMapper mapper = session.getMapper(UserMapper.class);
			UserPo userPo = new UserPo();
			userPo.setUserId(1000003l);
			userPo.setName("王五");
			userPo.setPassword("123456");
			userPo.setPhoneNum(15555555555l);
			userPo.setSex("女");
			userPo.setShippingAddress("重庆市");
			userPo.setUserName("小美女");
			System.out.println(userPo.toString());
			boolean flag = mapper.update(userPo);
			if(flag) {
				session.commit();
				System.out.println("更新成功");
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			session.close();
		}
	}
	
	public void testDelete() {
		
		//获取会话
		SqlSession session = MyBatisUtil.getSession();
		try {
			//获取接口的实现类对象
			//会自动为接口创建一个代理对象,代理对象去执行增删改查
			UserMapper mapper = session.getMapper(UserMapper.class);
			boolean flag = mapper.delete(1000003l);
			if(flag) {
				session.commit();
				System.out.println("删除成功");
				
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			session.close();
		}
	}
}

注意:

在mybatis中,对数据库操作,除了查询以外,其他的操作都需要进行提交 session.commit();,否则不会对数据库生效。

你可能感兴趣的:(mybatis框架学习)