对
时间: 2024-02-13 12:02:33 浏览: 52
好的,以下是示例代码:
Company.java:
```
public class Company {
private int id;
private String name;
private List<Employee> employees;
// getters and setters
// ...
// toString method
// ...
}
```
Employee.java:
```
public class Employee {
private int id;
private String name;
// getters and setters
// ...
// toString method
// ...
}
```
CompanyMapper.xml:
```
<mapper namespace="com.example.mapper.CompanyMapper">
<resultMap id="companyResultMap" type="com.example.model.Company">
<id property="id" column="id" />
<result property="name" column="name" />
<collection property="employees" ofType="com.example.model.Employee">
<id property="id" column="employee_id" />
<result property="name" column="employee_name" />
</collection>
</resultMap>
<select id="getCompanyById" resultMap="companyResultMap">
SELECT c.id, c.name, e.id AS employee_id, e.name AS employee_name
FROM Company c
LEFT JOIN Employee e ON c.id = e.company_id
WHERE c.id = #{id}
</select>
</mapper>
```
CompanyMapper.java:
```
public interface CompanyMapper {
Company getCompanyById(int id);
}
```
使用示例:
```
SqlSession sqlSession = sqlSessionFactory.openSession();
try {
CompanyMapper companyMapper = sqlSession.getMapper(CompanyMapper.class);
Company company = companyMapper.getCompanyById(1);
System.out.println(company);
} finally {
sqlSession.close();
}
```
需要注意的是,示例代码中的Mapper和Model类的命名可能需要根据你的实际情况进行调整。另外,示例代码中的SQL语句使用了LEFT JOIN,如果你的数据库中一个公司可能没有员工,那么可以使用该语句来查询。如果你的数据库中一个公司一定有员工,则可以使用INNER JOIN来查询。
阅读全文