本文主要是通过接口+映射文件的方式实现项目
一.创建一个java项目,新建javaProject
二.添加mybatis和mysql链接的jar包
三.创建数据库,特别注意创建外键
四.编写mybstis-cofig.xml配置文件
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<!-- mybatis-cofig配置文件 -->
<configuration>
<!--配置别名 -->
<typeAliases>
<typeAlias type="com.mybatis.one.to.many.pojo.User"
alias="user" />
</typeAliases>
<!-- 创建数据层 运行环境 -->
<environments default="development">
<environment id="development">
<!-- JDBC事务管理 -->
<transactionManager type="JDBC"></transactionManager>
<!-- 数据源 -->
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/test" />
<property name="username" value="root" />
<property name="password" value="110119" />
</dataSource>
</environment>
</environments>
<!-- 映射文件群 -->
<mappers>
<!-- 实体类对应的映射文件 -->
<mapper resource="com/mybatis/one/to/many/mapper/UserInterface.xml"/>
</mappers>
</configuration>
五.创建实体类
1)User.java 一对多关系中的一
/**
* @author wuchao
* @time 下午3:18:42
* @description TODO
*/
package com.mybatis.one.to.many.pojo;
import java.util.Date;
import java.util.List;
/**
* @author wuchao
* @time 下午3:18:42
*
*/
public class User {
private int id;
private String name;
private String dept;
private String phone;
private String website;
private Date createTimeDate;
private List<Post> posts;
/**
* @author wuchao
* @time 下午4:12:46
*/
public User() {
super();
// TODO Auto-generated constructor stub
}
/**
* @author wuchao
* @time 下午4:12:52
*/
public User(int id, String name, String dept, String phone, String website,
Date createTimeDate, List posts) {
super();
this.id = id;
this.name = name;
this.dept = dept;
this.phone = phone;
this.website = website;
this.createTimeDate = createTimeDate;
this.posts = posts;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDept() {
return dept;
}
public void setDept(String dept) {
this.dept = dept;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getWebsite() {
return website;
}
public void setWebsite(String website) {
this.website = website;
}
public Date getCreateTimeDate() {
return createTimeDate;
}
public void setCreateTimeDate(Date createTimeDate) {
this.createTimeDate = createTimeDate;
}
public List getPosts() {
return posts;
}
public void setPosts(List posts) {
this.posts = posts;
}
}
2)Post.java 一对多的多的类
/**
* @author wuchao
* @time 下午3:23:27
* @description TODO
*/
package com.mybatis.one.to.many.pojo;
/**
* @author wuchao
* @time 下午3:23:27
*
*/
public class Post {
private int id;
private String postName;
private String title;
private User user;
/**
* @author wuchao
* @time 下午3:26:36
*/
public Post() {
super();
// TODO Auto-generated constructor stub
}
/**
* @author wuchao
* @time 下午3:26:43
*/
public Post(int id, String postName, String title, User user) {
super();
this.id = id;
this.postName = postName;
this.title = title;
this.user = user;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getPostName() {
return postName;
}
public void setPostName(String postName) {
this.postName = postName;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
}
六.配置User接口
UserInterface.java
/**
* @author wuchao
* @time 下午3:27:16
* @description TODO
*/
package com.mybatis.one.to.many.dao;
import com.mybatis.one.to.many.pojo.User;
/**
* @author wuchao
* @time 下午3:27:16
*
*/
public interface UserInterface {
public User getUserById(int id);
}
七.实体类配置文件 在该配置文件中配置一对多的关系
UserInterface.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="com.mybatis.one.to.many.dao.UserInterface">
<resultMap type="user" id="resultUserMap">
<id property="id" column="id" />
<result property="name" column="name" />
<result property="dept" column="dept" />
<result property="phone" column="phone" />
<result property="website" column="website" />
<collection property="posts" ofType="com.mybatis.one.to.many.pojo.Post"
column="userId">
<id property="id" column="id"/>
<result property="postName" column="postName"/>
<result property="title" column="title"/>
</collection>
</resultMap>
<select id="getUserById" parameterType="user" resultMap="resultUserMap">
select u.* , p.*
from user u, post p
where u.id = p.userId and u.id = #{id}
</select>
</mapper>
在配置文件中配置collection 表示一对多的关系,其中property的参数值与User实体类中属性 private List posts的值保持一直,否则会报错
org.apache.ibatis.exceptions.PersistenceException:
### Error querying database. Cause: org.apache.ibatis.reflection.ReflectionException: There is no getter for property named 'postList' in 'class com.mybatis.one.to.many.pojo.User'
### The error may exist in com/mybatis/one/to/many/mapper/UserInterface.xml
### The error may involve com.mybatis.one.to.many.dao.UserInterface.getUserById
### The error occurred while handling results
### SQL: select u.* , p.* from user u, post p where u.id = p.userId and u.id = ?
### Cause: org.apache.ibatis.reflection.ReflectionException: There is no getter for property named 'postList' in 'class com.mybatis.one.to.many.pojo.User'
at org.apache.ibatis.exceptions.ExceptionFactory.wrapException(ExceptionFactory.java:30)
at org.apache.ibatis.session.defaults.DefaultSqlSession.selectList(DefaultSqlSession.java:150)
at org.apache.ibatis.session.defaults.DefaultSqlSession.selectList(DefaultSqlSession.java:141)
at org.apache.ibatis.session.defaults.DefaultSqlSession.selectOne(DefaultSqlSession.java:77)
at org.apache.ibatis.binding.MapperMethod.execute(MapperMethod.java:82)
at org.apache.ibatis.binding.MapperProxy.invoke(MapperProxy.java:59)
at com.sun.proxy.$Proxy2.getUserById(Unknown Source)
at com.mybatis.ome.to.many.test.Test.main(Test.java:47)
Caused by: org.apache.ibatis.reflection.ReflectionException: There is no getter for property named 'postList' in 'class com.mybatis.one.to.many.pojo.User'
at org.apache.ibatis.reflection.Reflector.getGetInvoker(Reflector.java:419)
at org.apache.ibatis.reflection.MetaClass.getGetInvoker(MetaClass.java:164)
at org.apache.ibatis.reflection.wrapper.BeanWrapper.getBeanProperty(BeanWrapper.java:162)
at org.apache.ibatis.reflection.wrapper.BeanWrapper.get(BeanWrapper.java:49)
at org.apache.ibatis.reflection.MetaObject.getValue(MetaObject.java:122)
at org.apache.ibatis.executor.resultset.DefaultResultSetHandler.instantiateCollectionPropertyIfAppropriate(DefaultResultSetHandler.java:1125)
at org.apache.ibatis.executor.resultset.DefaultResultSetHandler.applyNestedResultMappings(DefaultResultSetHandler.java:957)
at org.apache.ibatis.executor.resultset.DefaultResultSetHandler.getRowValue(DefaultResultSetHandler.java:914)
at org.apache.ibatis.executor.resultset.DefaultResultSetHandler.handleRowValuesForNestedResultMap(DefaultResultSetHandler.java:877)
at org.apache.ibatis.executor.resultset.DefaultResultSetHandler.handleRowValues(DefaultResultSetHandler.java:324)
at org.apache.ibatis.executor.resultset.DefaultResultSetHandler.handleResultSet(DefaultResultSetHandler.java:299)
at org.apache.ibatis.executor.resultset.DefaultResultSetHandler.handleResultSets(DefaultResultSetHandler.java:192)
at org.apache.ibatis.executor.statement.PreparedStatementHandler.query(PreparedStatementHandler.java:64)
at org.apache.ibatis.executor.statement.RoutingStatementHandler.query(RoutingStatementHandler.java:79)
at org.apache.ibatis.executor.SimpleExecutor.doQuery(SimpleExecutor.java:63)
at org.apache.ibatis.executor.BaseExecutor.queryFromDatabase(BaseExecutor.java:324)
at org.apache.ibatis.executor.BaseExecutor.query(BaseExecutor.java:156)
at org.apache.ibatis.executor.CachingExecutor.query(CachingExecutor.java:109)
at org.apache.ibatis.executor.CachingExecutor.query(CachingExecutor.java:83)
at org.apache.ibatis.session.defaults.DefaultSqlSession.selectList(DefaultSqlSession.java:148)
... 6 more
八.测试类 Test.java
“`
/**
* @author wuchao
* @time 下午3:50:07
* @description TODO
*/
package com.mybatis.ome.to.many.test;
import java.io.Reader;
import java.util.List;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import com.mybatis.one.to.many.dao.UserInterface;
import com.mybatis.one.to.many.pojo.Post;
import com.mybatis.one.to.many.pojo.User;
/**
* @author wuchao
* @time 下午3:50:07
*
*/
public class Test {
private static Reader reader;
private static SqlSessionFactory sqlSessionFactory;
static {
try {
reader = Resources.getResourceAsReader(“mybatis-config.xml”);
sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
public static SqlSessionFactory getSession() {
return sqlSessionFactory;
}
public static void main(String args[]) {
SqlSession session = sqlSessionFactory.openSession();
try {
UserInterface userInterface = session
.getMapper(UserInterface.class);
User user = userInterface.getUserById(1);
System.out.println("查询到的用户id是:" + user.getId());
System.out.println("查询到的用户名字是:" + user.getName());
System.out.println("查询到的用户网站:" + user.getWebsite());
List<Post> posts = user.getPosts();
for (Post post : posts) {
System.out.println("查询出来的post名字是:" + post.getPostName());
System.out.println("查询出来的post文本是:"+post.getTitle());
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}finally{
session.close();
}
}
}
“`