一个springboot+vue两表关联怎么写,注意是前后端分离的项目,把具体过程写出来
自己问题描述得简简单单,不清不楚;还特么要求别人把具体过程写出来;
在 Spring Boot 和 Vue.js 中,实现两个表的关联可以采用使用 RESTful API 进行数据交互和访问。
假设有两个表 A 和 B,这两个表通过一个外键关联,那么我们需要进行以下几个步骤:
@Entity
public class A {
// ...
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "b_id")
private B b;
// ...
}
@Entity
public class B {
// ...
}
在上面的代码中,@ManyToOne
注解表示 A 和 B 是多对一的关系,即一条记录在 A 表中只能指向 B 表中的一条记录。@JoinColumn
注解指定了 A 表中的外键字段名称为 "b_id",它将与 B 表中的主键字段进行匹配。
CrudRepository
接口:public interface ARepository extends CrudRepository<A, Long> {
// ...
}
public interface BRepository extends CrudRepository<B, Long> {
// ...
}
public interface ARepository extends CrudRepository<A, Long> {
@Query("SELECT a, a.b FROM A a")
List<Object[]> findAllWithB();
}
在上面的代码中,我们使用了 @Query
注解来定义一个 JPQL 查询语句,它将 A 表和 B 表关联查询,并将结果以数组形式返回。
@RestController
@RequestMapping("/api")
public class Controller {
@Autowired
private ARepository aRepository;
@Autowired
private BRepository bRepository;
@GetMapping("/a-with-b")
public List<AWithB> getAllAWithB() {
List<Object[]> results = aRepository.findAllWithB();
List<AWithB> aWithBs = new ArrayList<>();
for (Object[] result : results) {
A a = (A) result[0];
B b = (B) result[1];
aWithBs.add(new AWithB(a, b));
}
return aWithBs;
}
}
public class AWithB {
private A a;
private B b;
// 构造函数、getters 和 setters 略
}
在上面的代码中,我们编写了一个名为 getAllAWithB()
的 HTTP GET 请求处理方法,该方法将调用 A 仓库接口中的自定义查询方法,并将指向同一 B 记录的 A 记录和 B 记录封装到一个新的 AWithB 类型的对象中。最后,我们将所有的 AWithB 对象放到一个列表中并返回。
在 Vue.js 中,您可以使用 axios
库来发送 HTTP 请求,并使用 v-for
指令循环渲染数据。以下是一个简单的例子:
<template>
<div>
<table>
<thead>
<tr>
<th>A.id</th>
<th>B.name</th>
</tr>
</thead>
<tbody>
<tr v-for="ab in abs" :key="ab.a.id">
<td>{{ ab.a.id }}</td>
<td>{{ ab.b.name }}</td>
</tr>
</tbody>
</table>
</div>
</template>
<script>
import axios from 'axios';
export default {
data() {
return {
abs: []
};
},
mounted() {
this.getAllAWithB();
},
methods: {
getAllAWithB() {
axios.get('/api/a-with-b')
.then(response => {
this.abs = response.data;
})
.catch(error => {
console.log(error);
});
}
}
};
</script>
在上面的代码中,定义了一个 Vue.js 组件,并使用 axios
库在组件挂载时发送 HTTP GET 请求。在请求成功后,我们将响应数据赋值给组件的 abs
属性。最后,我们使用 v-for
指令循环渲染数据。