使用MyBatis进行对数据表的增删改查操作

1.导入jar包并配置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>
<!-- 
default="development":指定当前环境的模式,只有两个取值:
	development: 开发模式
	worker:工作模式
 -->
  <environments default="development">
  <!-- 
  id="development":指定当前的环境模式,只需要注意的是:当前id的取值必须和environments节点中default的取值相同
     -->
    <environment id="development">
    <!-- type="JDBC":指定当前的事务管理器为JDBC,大小写不敏感     -->
      <transactionManager type="JDBC"/>
      <!-- 
      type="POOLED":指定当前数据源的类型为连接池类型
       -->
      <dataSource type="POOLED">
      <!--   数据库连接信息       -->
        <property name="driver" value="com.mysql.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql:///test"/>
        <property name="username" value="root"/>
        <property name="password" value="zxczxc"/>
      </dataSource>
    </environment>
  </environments>
  <mappers>
  <!-- 注册自定义的映射文件 -->
    <mapper resource="com/gu/domain/Person.cfg.xml"/>
  </mappers>
</configuration>


2.创建实体类,并配置映射文件

package com.gu.domain;
import java.util.Date;
public class Person {
	private Integer id;
	private String name;
	private Integer age;
	private String sex;
	private Date birthday;
	public Person() {
		super();
		// TODO Auto-generated constructor stub
	}
	public Person(String name, Integer age, String sex, Date birthday) {
		super();
		this.name = name;
		this.age = age;
		this.sex = sex;
		this.birthday = birthday;
	}
	public Person(Integer id, String name, Integer age, String sex,
			Date birthday) {
		super();
		this.id = id;
		this.name = name;
		this.age = age;
		this.sex = sex;
		this.birthday = birthday;
	}
Setter、Getter方法(省略)。。。
	@Override
	public String toString() {
		return "Person [age=" + age + ", birthday=" + birthday + ", id=" + id
				+ ", name=" + name + ", sex=" + sex + "]";
	}
}

在以上的配置文件中,不管用户是进行对数据表的和中操作都要配置的,所以将以上两步提取出来,现分别对增删改查进行详细说明。

(1)插入数据操作

MyBatis是一个ORM框架,是一个基于JDBC的开源框架.其中数据库和相关表必须手工创建。

1、创建数据库以及数据表

create database  test;
create table t_person(
	id int primary key auto_increment,
	name varchar(20) unique not null,
	age int ,
	sex varchar(10) ,
	birthday date 
);
2、配置插入操作的实体类的映射文件

<?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.gu.domain.PersonMapper">
<insert id="insertPerson" parameterType="com.gu.domain.Person">
		insert into t_person values(null,#{name},#{age},#{sex},#{birthday});
	</insert>
</mapper>

说明:namespace="com.gu.domain.PersonMapper" 取值必须唯一,一般建议使用包名+类名

paramentType="com.gu.domain.Person"指定输入参数的数据类型(因为此处我们是插入一个person实体,所以用Person实体类

resultType="com.gu.domain.Person"指定输出参数的数据类型(只插入无输出情况,所以此处省略不写)

id=”insertPerson” :此处是insert语句的片段,并且id值必须唯一。命名要有规范!

#{ } 表示MyBatis特有的规范写法,使用在xml映射文件中。{ } 内填写与之对应的属性名。如果输入参数的数据类型(parameterType)是“int”类型的,{ }内可以任意填写,其余则不行。

3、测试类


public class test01 {
	public static void main(String[] args) {
		String resource = "myBatis.cfg.xml";
		try {
			InputStream inputStream = Resources.getResourceAsStream(resource);
			SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder()
					.build(inputStream);
			SqlSession sqlSession = sqlSessionFactory.openSession();
Person person = new Person("赵丽颖", 17, "女",new Date()); 
int count= sqlSession.insert("com.gu.domain.PersonMapper.insertPerson",person); sqlSession.commit();
System.out.println("count="+count);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}

说明:

· 如何构建SqlSessionFactory

XML 中构建 SqlSessionFactory步骤:

//1.得到输入流
String resource = "myBatis.cfg.xml";
inputStream=Resources.getResourceAsStream(resource);
//2.得到SqlSessionFactory对象
sqlSessionFactory=new SqlSessionFactoryBuilder().build(inputStream);
//3.得到SqlSession对象
//sqlSession=sqlSessionFactory.openSession();//默认事务不是自动提交的
sqlSession=sqlSessionFactory.openSession(true);//设置事务自动提交,则不需要手工提交事务了

·使用sqlSession.insert(statement,parameter)进行数据插入操作。

Statement:namespace+id的值(如:com.gu.domain.PersonMapper.insertPerson

Parameter:传入的属性值(如:person)

·在进行数据增删改时,必须手动进行事务提交才能在数据表中保存数据。所以在sqlSession.insert()方法后还需要手动的事务提交。事务提交调用sqlSession.commit()方法。

(2)查看数据操作

1、映射文件配置信息
<?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.gu.domain.PersonMapper">
	<select id="selectById" parameterType="int" resultType="com.gu.domain.Person">
		select *from t_person where id = #{id} ; <!-- 根据id进行查询 -->
  </select>
	<select id="selectAll" resultType="com.gu.domain.Person">
		select * from t_person ;   <!—查询所有 -->
	</select>
	<select id="selectLike" parameterType="string" resultType="com.gu.domain.Person">
		<!-- select * from t_person where name like #{name};-->
		select * from t_person where name like #{conditon}; <!—-  模糊查询 -->
	</select>
</mapper>
2、测试
public class test01 {
	public static void main(String[] args) {
		String resource = "myBatis.cfg.xml";
		try {
			InputStream inputStream = Resources.getResourceAsStream(resource);
			SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder()
					.build(inputStream);
			SqlSession sqlSession = sqlSessionFactory.openSession();
			  Person person =
			  sqlSession.selectOne("com.gu.domain.PersonMapper.selectById",1);
			/*
			 * List<Person> persons
			 * =sqlSession.selectList("com.gu.domain.PersonMapper.selectAll");
			 * System.out.println(persons);
			 */
			/*String condition = "赵";
			List<Person> person = sqlSession.selectList(
					"com.gu.domain.PersonMapper.selectLike",
					'%' + condition + '%');
			System.out.println(person);*/
			} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}

注意:

1selectOne和selectList 都可以查询到用户,但是两者有明显的区别:

SelectOne : 表示查询的用户是一个或者是0

SelectList :表示查询的用户是1个或者多个,返回的是list集合。

当对 对象进行查询时,必须使用SelectList方法。

2 在模糊查询时,Parameter传入的属性值要根据映射文件的模糊查询条件进行给定。模糊查询可能查出1个或者多个,所以说模糊查询必须使用selectList方法,返回List集合。


(3)修改数据操作

1、映射文件配置信息

<?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.gu.domain.PersonMapper">
<update id="updateById" parameterType="com.gu.domain.Person">
update t_person set name=#{name},age=#{age},sex=#{sex},birthday=#{birthday}
 where 	id=#{id};
  </update>
</mapper>

2、测试(先查询此用户是否存在,如果存在则进行修改用户信息)

public class test01 {
	public static void main(String[] args) {
		String resource = "myBatis.cfg.xml";
		try {
			InputStream inputStream = Resources.getResourceAsStream(resource);
			SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder()
					.build(inputStream);
			SqlSession sqlSession = sqlSessionFactory.openSession();
			sqlSession.selectOne("com.gu.domain.PersonMapper.selectById", 5);
			if(person!=null){
				person.setName("王思聪");
				person.setAge(28);
				person.setSex("女");
				person.setBirthday(new Date());
				sqlSession.update("com.gu.domain.PersonMapper.updateById",person);
				sqlSession.commit();
			}else{
				throw new RuntimeException("查不到此用户");
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}

说明:对用进行修改信息时,使用update语句。

(4)删除数据操作

1、映射文件配置信息

<?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.gu.domain.PersonMapper">
<delete id="deleteAll"> <!— 删除所有 -->
		delete from t_person;
</delete>
</mapper>

2、测试

public class test01 {
	public static void main(String[] args) {
		String resource = "myBatis.cfg.xml";
		try {
			InputStream inputStream = Resources.getResourceAsStream(resource);
			SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder()
					.build(inputStream);
			SqlSession sqlSession = sqlSessionFactory.openSession();
			int count=sqlSession.delete("com.gu.domain.PersonMapper.deleteAll");
			sqlSession.commit();
			System.out.println("coune="+count);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}

说明:删除操作时,直接调用delete方法。



















  • 5
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值