2018.10.14 MyBatis配置实现对用户的增删改查

记得导入对应的Jar包

ant-1.9.6.jar
ant-launcher-1.9.6.jar
asm-5.2.jar
cglib-3.2.5.jar
commons-logging-1.2.jar
javassist-3.22.0-GA.jar
log4j-1.2.17.jar
log4j-api-2.3.jar
log4j-core-2.3.jar
mybatis-3.4.6.jar
mysql-connector-java.jar
ognl-3.1.16.jar
slf4j-api-1.7.25.jar
slf4j-log4j12-1.7.25.jar

xml文件实现自动提示 先导入dtd的约束在jar包里面有:mybatis-3.4.6.jar ----> org.apache.ibatis.builder---->xml文件夹------>有两个以dtd结尾的文件,复制出来导如eclipse中

加入头部信息mapper

<?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">


加入头部信息config

<?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">

在src目录下面创建一个SqlMapConfig.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>
	<!-- 和spring整合后 environments配置将废除-->
	<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/mybaits?characterEncoding=utf-8" />
				<property name="username" value="root" />
				<property name="password" value="123456" />
			</dataSource>
		</environment>
	</environments>
	
	
	<!-- 加载po映射文件 -->
	<!-- <mappers>
		<mapper resource="com/mybatis/po/User.xml"/>
	</mappers> -->
	
	<!-- 动态代理模式  加载mapper映射文件 -->
	<mappers>
		<mapper resource="com/mybatis/mapper/UserMapper.xml"/>
	</mappers>
</configuration>

创建日志信息文件 log4j.properties

### 设置###
log4j.rootLogger = debug,stdout,D,E

### 输出信息到控制抬 ###
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 = [%-5p] %d{yyyy-MM-dd HH:mm:ss,SSS} method:%l%n%m%n

### 输出DEBUG 级别以上的日志到=E://logs/error.log ###
log4j.appender.D = org.apache.log4j.DailyRollingFileAppender
log4j.appender.D.File = E://logs/log.log
log4j.appender.D.Append = true
log4j.appender.D.Threshold = DEBUG 
log4j.appender.D.layout = org.apache.log4j.PatternLayout
log4j.appender.D.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss}  [ %t:%r ] - [ %p ]  %m%n

### 输出ERROR 级别以上的日志到=E://logs/error.log ###
log4j.appender.E = org.apache.log4j.DailyRollingFileAppender
log4j.appender.E.File =E://logs/error.log 
log4j.appender.E.Append = true
log4j.appender.E.Threshold = ERROR 
log4j.appender.E.layout = org.apache.log4j.PatternLayout
log4j.appender.E.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss}  [ %t:%r ] - [ %p ]  %m%n

创建实体对象

package com.mybatis.po;

import java.io.Serializable;
import java.util.Date;


public class User implements Serializable {
	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;
	}
	@Override
	public String toString() {
		return "User [id=" + id + ", username=" + username + ", sex=" + sex
				+ ", birthday=" + birthday + ", address=" + address + "]";
	}

	
	

}

UserMapper.java是一个接口

package com.mybatis.mapper;

import java.util.List;

import com.mybatis.po.User;

public interface UserMapper {
	//根据Id查找对象
	public User findUserById(int id) throws Exception;
	
	//模糊查找
	public List<User> findUserByLikeName(String username) throws Exception;

	//添加对象
	public void addUser(User user) throws Exception;
	
	//修改对象
	public void updateUser(User user) throws Exception;
}

UserMapper.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="com.mybatis.mapper.UserMapper">
	<!-- 
	查询操作
	根据id查询用户对象
	public User findUserById(int id){}
	 -->
	<select id="findUserById" parameterType="int" resultType="com.mybatis.po.User">
		select * from user where id=#{id}
	</select>
	
	<!-- 模糊查询  根据名字   返回的是集合对象 -->
	<select id="findUserByLikeName" parameterType="java.lang.String" resultType="com.mybatis.po.User">
		select * from user where username like '%${value}%'
	</select>
	
	
	
	 <!-- 插入操作 -->
	<insert id="insertUser" parameterType="com.mybatis.po.User">
		<!-- 主键映射 -->
		<selectKey keyProperty="id" order="AFTER" resultType="int">
			select LAST_INSERT_ID()
		</selectKey>
		
		insert into user(username,birthday,sex,address) values(#{username},#{birthday},#{sex},#{address})
	</insert> 
	
	
	<!-- 修改操作 -->
	<update id="updateUser" parameterType="com.mybatis.po.User">
		<!-- update user set username='小五' where id=1; -->
		update user set username=#{username},birthday=#{birthday},sex=#{sex},address=#{address} where id=#{id}
	</update>
	
	<!-- 删除操作 -->
	<delete id="delUser" parameterType="int">
		delete from user where id=#{id}
	</delete>
</mapper>

Test测试

package com.mybatis.test;
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.mybatis.mapper.UserMapper;
import com.mybatis.po.User;

public class TestMapper {
	//定义工厂对象
	private SqlSessionFactory sqlSessionFactory;
	
	@Before
	public void testCreateSqlsessionFactory()throws Exception {
		//创建sqlsession工厂
		sqlSessionFactory = new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream("SqlMapConfig.xml"));
	}
	
	
	//根据Id查询用户对象
	@Test
	public void testFindUserById() {
		//通过工厂对象生成sqlsession对象
		SqlSession session = sqlSessionFactory.openSession();
		UserMapper userMapper = session.getMapper(UserMapper.class);
		
		try {
			User user = userMapper.findUserById(10);
			System.out.println(user);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		//User user = session.selectOne("test.findUserById",10);//只能查询一条记录
		//System.out.println(user);
		session.close();
	}
	
	
	//模糊查询  根据名字
	@Test
	public void testFindUserByLikeName() {
		//通过工厂对象生成sqlsession对象
		SqlSession session = sqlSessionFactory.openSession();
		//根据反射
		UserMapper userMapper = session.getMapper(UserMapper.class);
			
		try {
			List<User> userList = userMapper.findUserByLikeName("张");
			System.out.println(userList.size());
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		session.close();
	}
	
	
	
	//插入数据
	@Test
	public void testInsertUser() {
		//通过工厂对象生成sqlsession对象
		SqlSession session = sqlSessionFactory.openSession();
		UserMapper userMapper = session.getMapper(UserMapper.class);
		
		//创建用户对象
		User user = new User();
		user.setAddress("广西");
		user.setBirthday(new Date());
		user.setSex("1");
		user.setUsername("legend");
		
		//session.insert("test.insertUser", user);
		try {
			//动态代理实现插入数据
			userMapper.addUser(user);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
		//实现事务提交
		session.commit();
		System.out.println("插入成功");
		//session.close();
	}
	
	
	//修改信息
	@Test
	public void testUpdateUser() {
		//通过工厂对象生成sqlsession对象
		SqlSession session = sqlSessionFactory.openSession();
		
		//User user = new User();
		UserMapper userMapper = session.getMapper(UserMapper.class);
		
		
		try {
			//先查找数据库里面的数据  获得修改的对象
			User user = userMapper.findUserById(10);
			
			user.setId(26);
			user.setAddress("广东广州");
			user.setBirthday(new Date());
			user.setSex("2");
			user.setUsername("五仁");
			//session.update("updateUser", user);
			userMapper.updateUser(user);
			session.commit();
			System.out.println("更新成功");
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		//session.close();
	}
	
	//删除
	@Test
	public void testDelUser() {
		//通过工厂对象生成sqlsession对象
		SqlSession session = sqlSessionFactory.openSession();
		session.delete("test.delUser", 28);
		session.commit();
		System.out.println("删除成功");
	}
}

posted @ 2018-10-14 15:19  LegendQi  阅读(395)  评论(0编辑  收藏  举报