标签:ati return type stat find nts table gets odi
1)如图
2)创建students.sql和cards.sql
drop table students;
drop table cards;
create table cards(
id int(5) primary key,
num varchar(20)
);
create table students(
id int(5) primary key,
name varchar(10),
cid int(5),
constraint cid_fk foreign key(cid) references cards(id)
);
insert into cards(id,num) values(1,‘111‘);
insert into students(id,name,cid) values(1,‘哈哈‘,1);
3)创建Students.java和Card.java
public class Card { private Integer id; private String num; private Student student; public Card(){} public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getNum() { return num; } public void setNum(String num) { this.num = num; } public Student getStudent() { return student; } public void setStudent(Student student) { this.student = student; } } public class Student { private Integer id; private String name; private Card card; public Student(){} public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Card getCard() { return card; } public void setCard(Card card) { this.card = card; } }
4)创建StudentMapper.xml和CardMapper.xml
CardMapper.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="cardNamespace"> <resultMap type="loaderman.one2one.Card" id="cardMap"> <id property="id" column="id" /> <result property="num" column="num" /> </resultMap> </mapper>
StudentMapper.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="studentNamespace"> <resultMap type="loaderman.one2one.Student" id="studentMap"> <id property="id" column="id" /> <result property="name" column="name"/> <association property="card" resultMap="cardNamespace.cardMap"/> </resultMap> <select id="findById" parameterType="int" resultMap="studentMap"> select s.id,s.name,c.id,c.num from students s inner join cards c on s.cid = c.id and s.id = #{id} </select> </mapper>
5)创建StudentCardDao.java
public class StudentCardDao { /** * 查询1号【学生】 */ public Student findById(int id) throws Exception{ SqlSession sqlSession = null; try{ sqlSession = MybatisUtil.getSqlSession(); return sqlSession.selectOne("studentNamespace.findById",id); }catch(Exception e){ e.printStackTrace(); throw e; }finally{ MybatisUtil.closeSqlSession(); } } public static void main(String[] args) throws Exception{ StudentCardDao dao = new StudentCardDao(); Student student = dao.findById(1); System.out.println(student.getId()+":"+student.getName()); System.out.println(student.getCard().getId()+":"+student.getCard().getNum()); } }
标签:ati return type stat find nts table gets odi
原文地址:https://www.cnblogs.com/loaderman/p/10064562.html