1.示例数据库准备:
1)增加创建示例表单:
CREATE TABLE TB_JOB ( id INT PRIMARY KEY AUTO_INCREMENT, id_person INT NOT NULL, job VARCHAR(60) NOT NULL, company VARCHAR(60) NOT NULL);
2)插入示例条目:
INSERT INTO TB_JOB (id_person, job, company)VALUES (3, "Singer", "BadBoy");INSERT INTO TB_JOB (id_person, job, company)VALUES (3, "writer", "BadBoy2");INSERT INTO TB_JOB (id_person, job, company)VALUES (3, "Producer", "BadBoy3");
3)增加创建JavaBean类BeanJob:
package cn.cvu.domain;public class BeanJob { private Integer id; private BeanPerson person; private String job; private String company; public Integer getId() {...} public void setId(Integer id) {...} public BeanPerson getPerson() {...} public void setPerson(BeanPerson person) {...} public String getJob() {...} public void setJob(String job) {...} public String getCompany() {...} public void setCompany(String company) {...} public BeanJob(Integer id, BeanPerson person, String job, String company) { this.id = id; this.person = person; this.job = job; this.company = company; } public BeanJob() { } @Override public String toString() { return "BeanJob [id=" + id + ", person=" + person + ", job=" + job + ", company=" + company + "]"; }}
2.修改接口:
package cn.cvu.service;import java.util.List;import cn.cvu.domain.BeanJob;//接口,定义操作public interface IOperationBean { //根据Person的id得到他全部的工作 public ListgetPersonJobs(int id);}
3.修改BeanPerson.xml文件:
1)方式一:
2)方式二:
4. 测试:
/** * 查询连接数据 * @throws Exception */ @Test public void testGetPersonJob() throws Exception { Reader reader = Resources.getResourceAsReader("Configuration.xml"); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader); SqlSession session = sqlSessionFactory.openSession(); IOperationBean operationBean = session.getMapper(IOperationBean.class); Listjobs = operationBean.getPersonJobs(3); for(BeanJob job:jobs){ System.out.println("人员ID:"+job.getPerson().getId()); System.out.println("姓名: "+job.getPerson().getName()); System.out.println("国家: "+job.getPerson().getCountry()); System.out.println("地址: "+job.getPerson().getAddress()); System.out.println("工作ID: "+job.getId()); System.out.println("工作: "+job.getJob()); System.out.println("公司: "+job.getCompany()); } session.close(); }
- end