spring boot里查询一张表的全部字段数据和另一张表的某个字段数据。
如下图所示是两张表
如上图,字段多的表名A,字段少的表叫B,A表内字段category_one,对应的是B表内字段dict_code,我要得到的是A表的全部数据,和根据那两个链接的字段,查对应的B表的dict_name,我写完总是报错Invalid bound statement (not found)
写的是jeecgboot单体项目,就是spring boot,只不过换了个框架而已,怎么写也写不出来,越写越乱,在网上看很多都是差不多的,哪位能指点我一下?
Entity层到底该哪个表引用另一张表的属性,是A引用B还是B引用A?,controller和service层不是正常写就可以了吗,,xml层具体该怎么写?照着网上写了很多遍,我始终映射不上。
整体就是entity,controller,service,mapper和mapper.xml
这就联表查询被 条件是 A.category_one = B.dict_code
比如 select a.*,b.dict_name from A a left join B b on a.category_one = b.dict_code;
我可以尝试给出以下解决方案: 1. 首先,在实体类中引用另一张表的属性需要使用@ManyToOne或@OneToOne注解,具体使用哪种注解取决于两张表之间的关系。例如,表A中和表B中对应的字段为a_id和b_id,且表A中的a_id对应表B中的一个唯一的b_id,则在表A对应的实体类中可以这样定义:
@Entity
@Table(name = "table_a")
public class TableAEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
@ManyToOne
@JoinColumn(name = "b_id", referencedColumnName = "id")
private TableBEntity tableBEntity;
//其他属性/方法
}
上述代码中,使用@ManyToOne注解引用了TableBEntity类,并指定了表A中对应表B的字段名和引用的的类型。 2. 在mapper层的XML文件中,需要使用关联查询的方式将两张表的数据查询出来,同时还需要使用到“resultMap”配置,例如:
<!--定义resultMap-->
<resultMap id="tableJoinMap" type="com.example.entity.TableAEntity">
<id column="id" property="id"/>
<result column="name" property="name"/>
<association property="tableBEntity" resultMap="com.example.mapper.TableBMapper.tableBResultMap"/>
</resultMap>
<!--定义SQL查询语句-->
<select id="selectTableJoinData" resultMap="tableJoinMap">
SELECT a.*, b.column_b FROM table_a a LEFT JOIN table_b b ON a.b_id = b.id WHERE a.id = #{id}
</select>
上述代码中,“resultMap”配置先定义了一个名为“tableJoinMap”的查询结果映射,其中id、name和tableBEntity三个字段分别对应了表A和表B中的字段,其中tableBEntity字段使用了“association”配置来引用另一个resultMap,并通过resultMap的名字指定了要引用的TableBMapper中的查询结果映射。 3. 在Service层和Controller层中,可以通过调用mapper中定义的查询语句来查询数据:
@Service
public class TableAService {
@Autowired
private TableAMapper tableAMapper;
@Autowired
private TableBMapper tableBMapper;
public TableAEntity selectTableJoinData(Long id) {
TableAEntity tableAEntity = tableAMapper.selectTableJoinData(id);
TableBEntity tableBEntity = tableBMapper.selectTableBData(tableAEntity.getTableBEntity().getId());
tableAEntity.setTableBEntity(tableBEntity);
return tableAEntity;
}
}
@RestController
@RequestMapping("/table")
public class TableController {
@Autowired
private TableAService tableAService;
@GetMapping("/{id}")
public TableAEntity getTableJoinData(@PathVariable("id") Long id) {
return tableAService.selectTableJoinData(id);
}
}
上述代码中,TableAService中通过注入TableAMapper和TableBMapper来调用mapper层中定义的查询语句,然后再通过TableBMapper查询出对应的TableBEntity对象,并将它设置到TableAEntity中的tableBEntity属性中,最后返回TableAEntity对象。在TableController中通过调用TableAService来获取数据并返回。需要注意的是,在这个例子中,可能需要做一些空引用和空指针判断。