如何使用JPA和@Query命名参数将数据导入MySQL

时间:2015-05-02 07:36:17

标签: java mysql spring hibernate jpa

我收到以下错误:

Using named parameters for method public static void com.htd.repository.MaterialRepository.uploadMaterialData(java.lang.String,java.math.BigDecimal,java.lang.String,java.math.BigDecimal,java.math.BigDecimal) but parameter 'material_number' not found in annotated query 'INSERT INTO hillcresttooldie VALUES (?,?,?,?,?)'!

我在下面阅读了文件: http://docs.spring.io/spring-data/jpa/docs/1.4.3.RELEASE/reference/html/jpa.repositories.html但我仍有问题。我的印象是JPA为我们创建了查询。我习惯于写出这些问题,直到我发现这个令人敬畏的技术。

public interface MaterialRepository extends JpaRepository<Material,Long> {

    @Query("INSERT INTO hillcresttooldie VALUES (?,?,?,?,?)")
    static void uploadMaterialData(String material_number,BigDecimal material_thickness,String material_size,BigDecimal lb_per_sheet,BigDecimal dollar_per_lb) {


    }
}

尝试在MaterialResource.java文件中使用该查询

//puts materials into map and the key is the material number
                materialMap.put(materialValue, material);

                MaterialRepository.uploadMaterialData(material.getMaterial_number(), material.getMaterial_thickness(),
                        material.getMaterial_size(), material.getLb_per_sheet(), material.getDollar_per_lb());

2 个答案:

答案 0 :(得分:0)

将您的代码更改为

@Query("INSERT INTO hillcresttooldie (material_number,material_thickness,material_size,lb_per_sheet,dollar_per_lb) VALUES (:number, :thickness, :size, :lbPerSheet, :dollarPerLb)")
void uploadMaterialData(String number, BigDecimal thickness, String size, BigDecimal lbPerSheet, BigDecimal dollarPerLb)

答案 1 :(得分:0)

尝试:

public interface MaterialRepository extends JpaRepository<Material,Long> {

@Modifying
@Query(nativeQuery = true,"INSERT INTO hillcresttooldie(material_number,material_thickness,material_size,lb_per_sheet,dollar_per_lb) VALUES (?1,?2,?3,?4,?5)")
static void uploadMaterialData(String material_number,BigDecimal material_thickness,String material_size,BigDecimal lb_per_sheet,BigDecimal dollar_per_lb) {


}

}

public interface MaterialRepository extends JpaRepository<Material,Long> {

@Query("INSERT INTO hillcresttooldie(material_number) VALUES (:material_number)") //....
static void uploadMaterialData(@Param("material_number") String material_number) {


}

}