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

短命女 2022-06-14 02:30 351阅读 0赞

1.导入jar包并配置MyBatis的配置文件

  1. <?xml version="1.0" encoding="UTF-8" ?>
  2. <!DOCTYPE configuration
  3. PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
  4. "http://mybatis.org/dtd/mybatis-3-config.dtd">
  5. <configuration>
  6. <!--
  7. default="development":指定当前环境的模式,只有两个取值:
  8. development: 开发模式
  9. worker:工作模式
  10. -->
  11. <environments default="development">
  12. <!--
  13. id="development":指定当前的环境模式,只需要注意的是:当前id的取值必须和environments节点中default的取值相同
  14. -->
  15. <environment id="development">
  16. <!-- type="JDBC":指定当前的事务管理器为JDBC,大小写不敏感 -->
  17. <transactionManager type="JDBC"/>
  18. <!--
  19. type="POOLED":指定当前数据源的类型为连接池类型
  20. -->
  21. <dataSource type="POOLED">
  22. <!-- 数据库连接信息 -->
  23. <property name="driver" value="com.mysql.jdbc.Driver"/>
  24. <property name="url" value="jdbc:mysql:///test"/>
  25. <property name="username" value="root"/>
  26. <property name="password" value="zxczxc"/>
  27. </dataSource>
  28. </environment>
  29. </environments>
  30. <mappers>
  31. <!-- 注册自定义的映射文件 -->
  32. <mapper resource="com/gu/domain/Person.cfg.xml"/>
  33. </mappers>
  34. </configuration>

#

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

  1. package com.gu.domain;
  2. import java.util.Date;
  3. public class Person {
  4. private Integer id;
  5. private String name;
  6. private Integer age;
  7. private String sex;
  8. private Date birthday;
  9. public Person() {
  10. super();
  11. // TODO Auto-generated constructor stub
  12. }
  13. public Person(String name, Integer age, String sex, Date birthday) {
  14. super();
  15. this.name = name;
  16. this.age = age;
  17. this.sex = sex;
  18. this.birthday = birthday;
  19. }
  20. public Person(Integer id, String name, Integer age, String sex,
  21. Date birthday) {
  22. super();
  23. this.id = id;
  24. this.name = name;
  25. this.age = age;
  26. this.sex = sex;
  27. this.birthday = birthday;
  28. }
  29. SetterGetter方法(省略)。。。
  30. @Override
  31. public String toString() {
  32. return "Person [age=" + age + ", birthday=" + birthday + ", id=" + id
  33. + ", name=" + name + ", sex=" + sex + "]";
  34. }
  35. }

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

(1)插入数据操作

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

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

  1. create database test;
  2. create table t_person(
  3. id int primary key auto_increment,
  4. name varchar(20) unique not null,
  5. age int ,
  6. sex varchar(10) ,
  7. birthday date
  8. );

2、配置插入操作的实体类的映射文件

  1. <?xml version="1.0" encoding="UTF-8" ?>
  2. <!DOCTYPE mapper
  3. PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  4. "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
  5. <mapper namespace="com.gu.domain.PersonMapper">
  6. <insert id="insertPerson" parameterType="com.gu.domain.Person">
  7. insert into t_person values(null,#{name},#{age},#{sex},#{birthday});
  8. </insert>
  9. </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、测试类

  1. public class test01 {
  2. public static void main(String[] args) {
  3. String resource = "myBatis.cfg.xml";
  4. try {
  5. InputStream inputStream = Resources.getResourceAsStream(resource);
  6. SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder()
  7. .build(inputStream);
  8. SqlSession sqlSession = sqlSessionFactory.openSession();
  9. Person person = new Person("赵丽颖", 17, "女",new Date());
  10. int count= sqlSession.insert("com.gu.domain.PersonMapper.insertPerson",person); sqlSession.commit();
  11. System.out.println("count="+count);
  12. } catch (IOException e) {
  13. e.printStackTrace();
  14. }
  15. }
  16. }

说明:

· 如何构建**SqlSessionFactory**?

从 XML 中构建 SqlSessionFactory步骤:

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

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

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

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

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

(2)查看数据操作

1、映射文件配置信息

  1. <?xml version="1.0" encoding="UTF-8" ?>
  2. <!DOCTYPE mapper
  3. PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  4. "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
  5. <mapper namespace="com.gu.domain.PersonMapper">
  6. <select id="selectById" parameterType="int" resultType="com.gu.domain.Person">
  7. select *from t_person where id = #{id} ; <!-- 根据id进行查询 -->
  8. </select>
  9. <select id="selectAll" resultType="com.gu.domain.Person">
  10. select * from t_person ; <!—查询所有 -->
  11. </select>
  12. <select id="selectLike" parameterType="string" resultType="com.gu.domain.Person">
  13. <!-- select * from t_person where name like #{name};-->
  14. select * from t_person where name like #{conditon}; <!—- 模糊查询 -->
  15. </select>
  16. </mapper>

2、测试

  1. public class test01 {
  2. public static void main(String[] args) {
  3. String resource = "myBatis.cfg.xml";
  4. try {
  5. InputStream inputStream = Resources.getResourceAsStream(resource);
  6. SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder()
  7. .build(inputStream);
  8. SqlSession sqlSession = sqlSessionFactory.openSession();
  9. Person person =
  10. sqlSession.selectOne("com.gu.domain.PersonMapper.selectById",1);
  11. /*
  12. * List<Person> persons
  13. * =sqlSession.selectList("com.gu.domain.PersonMapper.selectAll");
  14. * System.out.println(persons);
  15. */
  16. /*String condition = "赵";
  17. List<Person> person = sqlSession.selectList(
  18. "com.gu.domain.PersonMapper.selectLike",
  19. '%' + condition + '%');
  20. System.out.println(person);*/
  21. } catch (IOException e) {
  22. // TODO Auto-generated catch block
  23. e.printStackTrace();
  24. }
  25. }
  26. }

注意:

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

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

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

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

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

(3)修改数据操作

1、映射文件配置信息

  1. <?xml version="1.0" encoding="UTF-8" ?>
  2. <!DOCTYPE mapper
  3. PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  4. "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
  5. <mapper namespace="com.gu.domain.PersonMapper">
  6. <update id="updateById" parameterType="com.gu.domain.Person">
  7. update t_person set name=#{name},age=#{age},sex=#{sex},birthday=#{birthday}
  8. where id=#{id};
  9. </update>
  10. </mapper>

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

  1. public class test01 {
  2. public static void main(String[] args) {
  3. String resource = "myBatis.cfg.xml";
  4. try {
  5. InputStream inputStream = Resources.getResourceAsStream(resource);
  6. SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder()
  7. .build(inputStream);
  8. SqlSession sqlSession = sqlSessionFactory.openSession();
  9. sqlSession.selectOne("com.gu.domain.PersonMapper.selectById", 5);
  10. if(person!=null){
  11. person.setName("王思聪");
  12. person.setAge(28);
  13. person.setSex("女");
  14. person.setBirthday(new Date());
  15. sqlSession.update("com.gu.domain.PersonMapper.updateById",person);
  16. sqlSession.commit();
  17. }else{
  18. throw new RuntimeException("查不到此用户");
  19. }
  20. } catch (IOException e) {
  21. e.printStackTrace();
  22. }
  23. }
  24. }

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

(4)删除数据操作

1、映射文件配置信息

  1. <?xml version="1.0" encoding="UTF-8" ?>
  2. <!DOCTYPE mapper
  3. PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  4. "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
  5. <mapper namespace="com.gu.domain.PersonMapper">
  6. <delete id="deleteAll"> <!— 删除所有 -->
  7. delete from t_person;
  8. </delete>
  9. </mapper>

2、测试

  1. public class test01 {
  2. public static void main(String[] args) {
  3. String resource = "myBatis.cfg.xml";
  4. try {
  5. InputStream inputStream = Resources.getResourceAsStream(resource);
  6. SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder()
  7. .build(inputStream);
  8. SqlSession sqlSession = sqlSessionFactory.openSession();
  9. int count=sqlSession.delete("com.gu.domain.PersonMapper.deleteAll");
  10. sqlSession.commit();
  11. System.out.println("coune="+count);
  12. } catch (IOException e) {
  13. e.printStackTrace();
  14. }
  15. }
  16. }

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

发表评论

表情:
评论列表 (有 0 条评论,351人围观)

还没有评论,来说两句吧...

相关阅读