Mybatis框架|添加操作


问题说明:使用Mybatis框架向数据表中添加一条记录。

一、使用Mybatis进行添加操作

1.创建数据库表user

创建数据库表,并添加记录。

CREATE TABLE `user` (
	`id` INT(20)  AUTO_INCREMENT COMMENT '主键',
	`username` VARCHAR(50) NULL DEFAULT NULL COMMENT '姓名',
	`sex` VARCHAR(1) NULL DEFAULT NULL COMMENT '性别',
	`address` VARCHAR(200) NULL DEFAULT NULL COMMENT '住址',
	`birthday` DATE NULL DEFAULT NULL COMMENT '生日',
	PRIMARY KEY (`id`)
)
COLLATE='utf8_general_ci'
ENGINE=InnoDB
AUTO_INCREMENT=1
;
insert INTO user(id,username,sex,address,birthday) VALUE(NULL,'程蝶衣','男','广东','1997-11-22');
insert INTO user(id,username,sex,address,birthday) VALUE(NULL,'程小楼','男','湖南','1996-3-21');
insert INTO user(id,username,sex,address,birthday) VALUE(NULL,'周冬雨','女','湖北','1999-2-11');

在这里插入图片描述

2.JavaBean

package com.gql.pojo;
import java.io.Serializable;
import java.util.Date;
/**
 * 类说明:
 *		JavaBean
 * @guoqianliang1998.
 */
public class User implements Serializable{

	private static final long serialVersionUID = 1L;
	private int id;
	private String name;
	private String sex;
	private String address;
	private Date birthday;
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	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;
	}
	public Date getBirthday() {
		return birthday;
	}
	public void setBirthday(Date birthday) {
		this.birthday = birthday;
	}
}

3.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>
	<environments default="development">
		<environment id="development">
			<transactionManager type="JDBC" />
			<dataSource type="POOLED">
				<property name="driver" value="com.mysql.jdbc.Driver" />
				<property name="url" value="jdbc:mysql://localhost:3306/mybatis" />
				<property name="username" value="root" />
				<property name="password" value="Hudie" />
			</dataSource>
		</environment>
	</environments>
	<mappers>
		<mapper resource="User.xml" />
	</mappers>
</configuration>

4.User.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="test">
	<insert id="sql3" parameterType="com.gql.pojo.User">
		insert into user
		(username,sex,address,birthday)
		values(#{name},#{sex},#{address},#{birthday});
	</insert>
</mapper>

5.添加操作测试

package com.gql.Demo;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
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.gql.pojo.User;
/**
 * 类说明:
 *		测试使用Mybatis向数据库中添加记录
 * @guoqianliang1998.
 */
public class Demo {
	private SqlSessionFactory sqlSessionFactory;
	@Before
	public void init() throws IOException{
		String resource = "mybatis-config.xml";
		InputStream in = Resources.getResourceAsStream(resource);
		sqlSessionFactory = new SqlSessionFactoryBuilder().build(in);
		
	}
	
	@Test
	public void testSelectList(){
		SqlSession session = sqlSessionFactory.openSession();
		try {
			User user = new User();
			user.setName("王小花");
			user.setSex("女");
			user.setAddress("洛阳");
			user.setBirthday(new Date());
			session.insert("test.sql3",user);
			session.commit();
		}finally{
			session.close();
		}
	}
}

添加成功:
在这里插入图片描述

二、获取用户组件

再次向数据库中插入一条记录,commit提交后打印出ID值,会发现并不能真正获得ID,而是输出了0。

package com.gql.Demo;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
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.gql.pojo.User;
/**
 * 类说明:
 *		1.第一个Mybatis程序:打印出数据库中的一条记录
 *		2.测试使用Mybatis进行模糊查询
 *		3.测试使用Mybatis向数据库中添加记录
 * @guoqianliang1998.
 */
public class Demo {
	private SqlSessionFactory sqlSessionFactory;
	@Before
	public void init() throws IOException{
		String resource = "mybatis-config.xml";
		InputStream in = Resources.getResourceAsStream(resource);
		sqlSessionFactory = new SqlSessionFactoryBuilder().build(in);
		
	}

	
	@Test
	public void testSelectList(){
		SqlSession session = sqlSessionFactory.openSession();
		try {
			User user = new User();
			user.setName("郭德纲");
			user.setSex("男");
			user.setAddress("北京");
			user.setBirthday(new Date());
			session.insert("test.sql3",user);
			session.commit();
			System.out.println(user.getId());
		}finally{
			session.close();
		}
	}
}

在这里插入图片描述


正确的做法是下面的方式

1.自增长的主键

获取主键需要添加selectKey标签,selectKey中的sql语句为select last_insert_ID();其中的order属性为"AFTER"

selectKey标签中的属性:

扫描二维码关注公众号,回复: 9018290 查看本文章
  • selectKey:用于返回主键,定义sql语句。
  • parameterType:将主键和pojo中的属性进行映射。
  • order:selectKey中的sql语句相对于insert语句的执行顺序。
  • resultType:selectKey 中sql语句的结果类型。
<?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">
	<insert id="sql3" parameterType="com.gql.pojo.User">
		<selectKey keyProperty="id" order="AFTER" resultType="int">
			select last_insert_ID();
		</selectKey>
		insert into user
		(username,sex,address,birthday)
		values(#{name},#{sex},#{address},#{birthday});
	</insert>
</mapper>

再次测试,发现成功插入并打印出ID值:

	@Test
	public void testSelectList(){
		SqlSession session = sqlSessionFactory.openSession();
		try {
			User user = new User();
			user.setName("周润发");
			user.setSex("男");
			user.setAddress("北京");
			user.setBirthday(new Date());
			session.insert("test.sql3",user);
			session.commit();
			System.out.println(user.getId());
		}finally{
			session.close();
		}
	}

在这里插入图片描述
在这里插入图片描述

2.不是自增长的主键

主键是UUID的和上面的类似,只是将selectKey语句换成了select UUID();将order的属性换成了"BEFORE"

<?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">
	<insert id="sql3" parameterType="com.gql.pojo.User">
		<selectKey keyProperty="id" order="BEFORE" resultType="int">
			select UUID();
		</selectKey>
		insert into user
		(username,sex,address,birthday)
		values(#{name},#{sex},#{address},#{birthday});
	</insert>
</mapper>
发布了396 篇原创文章 · 获赞 1050 · 访问量 22万+

猜你喜欢

转载自blog.csdn.net/weixin_43691058/article/details/104226174