(3)创建Company类和Employee类,在Company类中添加Employee属性和name属性,在Employee类中添加name属性,在数据库创建Company表和Employee表,通过MyBatis查询id为1的Company类的信息(Company类中需要含有所属的Employee类的列表)。
时间: 2024-02-20 22:00:08 浏览: 116
好的,我来回答您的问题。
首先,我们可以定义Company类和Employee类如下:
```
public class Company {
private int id;
private String name;
private List<Employee> employees;
// getter and setter methods
}
public class Employee {
private int id;
private String name;
private int companyId;
// getter and setter methods
}
```
在Company类中添加了一个employees属性,用于存储所属的Employee类的列表。在Employee类中添加了一个companyId属性,用于表示所属的Company类的id。
接下来,我们需要在数据库中创建对应的Company表和Employee表,并进行关联。示例的SQL语句如下:
```
CREATE TABLE company (
id INT PRIMARY KEY,
name VARCHAR(50)
);
CREATE TABLE employee (
id INT PRIMARY KEY,
name VARCHAR(50),
company_id INT,
FOREIGN KEY (company_id) REFERENCES company(id)
);
```
创建完数据库表之后,我们可以在Mapper接口中定义查询方法,如下所示:
```
public interface CompanyMapper {
@Select("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}")
@Results({
@Result(property = "id", column = "id"),
@Result(property = "name", column = "name"),
@Result(property = "employees", column = "employee_id",
many = @Many(select = "com.example.EmployeeMapper.getEmployeeByCompanyId"))
})
Company getCompanyById(int id);
}
public interface EmployeeMapper {
@Select("SELECT * FROM employee WHERE company_id = #{companyId}")
List<Employee> getEmployeeByCompanyId(int companyId);
}
```
在CompanyMapper中定义了一个getCompanyById方法,根据id查询Company类的信息,并使用@Results注解来将查询结果映射到Company类的属性上。在employees属性上,使用@Many注解来表示一对多的关系,并使用getEmployeeByCompanyId方法来查询对应的Employee类列表。
在EmployeeMapper中定义了一个getEmployeeByCompanyId方法,根据companyId查询对应的Employee列表。
这样,我们就可以通过MyBatis查询id为1的Company类的信息,包含所属的Employee类的列表。
阅读全文