为了账号安全,请及时绑定邮箱和手机立即绑定

Mybatis如何实现对象的更新?

Mybatis如何实现对象的更新?

繁星点点滴滴 2019-02-20 09:20:10
现在有这样两张表: CREATE TABLE STUDENTS ( stud_id int(11) NOT NULL AUTO_INCREMENT, name varchar(50) NOT NULL, email varchar(50) NOT NULL, phone_number varchar(15) NULL, dob date DEFAULT NULL, address_id int(11) NOT NULL, PRIMARY KEY (stud_id) ) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8; /*Sample Data for the students table */ insert into students(stud_id,name,email,dob,address_id) values (1,'Student1','student1@gmail.com','1983-06-25',1); insert into students(stud_id,name,email,dob) values (2,'Student2','student2@gmail.com','1983-06-25',2); CREATE TABLE ADDRESS ( address_id int(11) NOT NULL AUTO_INCREMENT, city varchar(50) NOT NULL, state varchar(50) NOT NULL, PRIMARY KEY (address_id) ) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8; insert into address(city,state) values('北京','北京'); insert into address(city,state) values('上海','上海'); 对于关联查询,是比较简单的: <?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"> <!-- type 就是java类型 resultMap就是java类属性名与表字段名的映射--> <mapper namespace="com.mybatis.mappers.StudentMapper"> <resultMap type="com.mybatis.mappers.Student" id="StudentResult"> <id property="studId" column="stud_id" /> <result property="name" column="name" /> <result property="email" column="email" /> <result property="dob" column="dob" /> <result property="address.addressId" column="address_id"/> <result property="address.city" column="city"/> <result property="address.state" column="state"/> </resultMap> <select id="selectStudents" resultMap="StudentResult"> select students.*,address.* from students left outer join address on students.address_id=address.address_id </select> </mapper> 这样,就能实现面向对象式的查询。 但是,如何实现面向对象式的更新呢?比如,外在的API接口是如下的: @Test public void testStudent() throws IOException{ InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml"); SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(inputStream); SqlSession session= factory.openSession(); session.getConnection(); /* * XML文件与Mapper类的名字保持一致,就能自动关联映射。 * */ StudentMapper mapper = session.getMapper(StudentMapper.class); List<Student> students= mapper.selectStudents(); for (Student student : students) { //更新了Address: student.getAddress().setCity("西安"); //直接实现保存:更改的实际上是Address这个表: mapper.save(student); } }
查看完整描述

1 回答

?
MYYA

TA贡献1868条经验 获得超4个赞

想了一下,这种需求好像在关系型数据库中间比较奇葩。。。在nosql当中倒是比较常见。

查看完整回答
反对 回复 2019-03-01
  • 1 回答
  • 0 关注
  • 2287 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信