在Spring Data JPA中联接多个表

时间:2018-10-25 11:24:09

标签: spring hibernate spring-data-jpa

我是Spring Data JPA的新手,在连接两个表时遇到问题。

我有两个表:ProductType

Product的字段为product_nonamecosttype_id

Type具有字段idname。我能够从Product表中提取数据,但无法显示Type名称以及产品详细信息。包含数据的表如下:

Table : product

id      product_no  name                     type_id
1       kts2018        Kites tracker         1
2       jt2018           Jira  tracker           1
3       st2018          Strike seeker         2

Table:  type

id       name
1        Tracker
2        Seeker

实体如下:

产品

@Entity
@Table(name = "product")
public class Product implements Serializable {
    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "product_no")
    private String product_no;
    @Column(name = "name")
    private String name;
    @ManyToOne
    @JoinColumn(name = "type_id")
    private Type type;


    public String getProduct_no() {
        return product_no;
    }

    public void setProduct_no(String product_no) {
        this.product_no = product_no;
    }

    public Level getType() {
        return type;
    }

    public void setType(Type type) {
        this.type = type;
    }

类型

@Entity
@Table(name = "type")
public class Type implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int id;
@Column(name = "name")
private String name;

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public int getId() {
    return id;
}

public void setId(int id) {
    this.id = id;
}

我正在使用以下代码从产品表中提取数据:-

public interface ProductRepository extends JpaRepository<Product, Long> {

    @Query("select product, product.type.name FROM Product product where product.type.id=1")
    List<Product> getAllUserProducts();
}

控制器如下:-

@GetMapping("secure/product-details")
    public ModelAndView getAllUserProducts() {
        ModelAndView mav = new ModelAndView();
        mav.addObject("userProducts", userInfoService.getAllUserProducts());
        mav.setViewName("products");
    return mav;
}

products.html

<tr th:each="product: ${userProducts}">
                                    <td th:text="${product.product_no}"></td>                                                                           
                                    <td th:text="${product.type.name}"></td>

                                    <td><a class="btn-info btn-sm" style="border-radius: 4px"
                                        th:href="${'/show/' + product.product_no}">Process</a></td>
                                </tr>

现在我出现Thymeleaf错误。

它说

Exception evaluating SpringEL expression: "product.product_no"

0 个答案:

没有答案