mybatis的多表查询,映射到实体的应用(一)

先来个一对多的案例,一个人有多条评论

person

id        name

p001   小王

p002   小李

comment

-----------------------------------------------------

id        content   personid

3        四点半v    p001
2        第三个     p002
1        哈哈去     p001

----------------------------------------------------------------------

新建类

package model;

public class Person {
  private String id;
  private String name;
public String getId() {
	return id;
}
public void setId(String id) {
	this.id = id;
}
public String getName() {
	return name;
}
public void setName(String name) {
	this.name = name;
}
public Person(){
}
public Person(String _id,String _name){
	super();
	this.id=_id;
	this.name=_name;
}
  
}

 

package model;

public class Comment {
	int id;
	String content;
	String personid;
	Person person;
	public Person getPerson() {
		return person;
	}
	public void setPerson(Person person) {
		this.person = person;
	}
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getContent() {
		return content;
	}
	public void setContent(String content) {
		this.content = content;
	}
	public String getPersonid() {
		return personid;
	}
	public void setPersonid(String personid) {
		this.personid = personid;
	}
	
	public Comment(){
		
	}
	public Comment(int _id,String _content,String _personid){
		super();
		this.id=_id;
		this.content=_content;
		this.personid=_personid;
	}
}


src下新建commentMapper.xml






   
   
    


        
    


src下新建mybatis-config.xml




	
		
			
			
				
				
				
				
			
		
	
	

		
	


java代码:

 String resource = "mybatis-config.xml";
  InputStream  inputStream = Resources.getResourceAsStream(resource);
  SqlSessionFactory sqlSessionFactory =  new SqlSessionFactoryBuilder().build(inputStream);//工厂类用单例模式

 SqlSession session = sqlSessionFactory.openSession();
  try {
  Comment p = (Comment)session.selectOne("younamespace.selectComment", 1);
  System.out.print(p.getContent()+" 来自 "+p.getPerson().getName());
  } finally {
  session.close();
  }

结果:

哈哈去 来自 小王

 


 

你可能感兴趣的:(java开发)