如何使用spring jdbc在mysql中插入外键

时间:2014-02-14 18:32:58

标签: java mysql datasource foreign-key-relationship spring-jdbc

所以目前以下代码正常工作并从我的java应用程序插入到mysql中:

String sql = "INSERT INTO location(address1, address2, postcode, town)";
sql+= "VALUES(:address1, :address2, :postcode, :town)";

Map parameters = new HashMap();
parameters.put("address1", location.getAddress1());
parameters.put("address2", location.getAddress2());
parameters.put("postcode", location.getPostCode());
parameters.put("town", location.getTown());

this.namedParameterJdbcTemplate.update(sql, parameters);

但是,我不确定如何在位置表中添加“类型”列。此列/属性与另一个名为location_type的表相关。所以,如果我是通过mysql代码插入它我

INSERT INTO location(address1, address2, postcode, town, type)
VALUES("2","abc street","ab1 1cd", "nice town", (SELECT id FROM location_type WHERE type="main")  ) 

我如何从Java应用程序中执行此操作?

2 个答案:

答案 0 :(得分:2)

您可以在Java应用程序中以相同的方式执行此操作:

String sql = "INSERT INTO location(address1, address2, postcode, town, type)";
             + " VALUES (:address1, :address2, :postcode, :town,"
                           + " (SELECT id FROM location_type WHERE type='main'))";

Map parameters = new HashMap();
parameters.put("address1", address1);
parameters.put("address2", address2);
parameters.put("postcode", postcode);
parameters.put("town", town);

this.namedParameterJdbcTemplate.update(sql, parameters);

数据库没有理由从命令行接受SQL查询,并且当它来自Java应用程序时拒绝它。

如果上面的硬编码主要是另一个参数,你可以设置它与所有其他参数相同:

String sql = "INSERT INTO location(address1, address2, postcode, town, type)";
             + " VALUES (:address1, :address2, :postcode, :town,"
                           + " (SELECT id FROM location_type WHERE type= : type))";

Map parameters = new HashMap();
parameters.put("address1", address1);
parameters.put("address2", address2);
parameters.put("postcode", postcode);
parameters.put("town", town);
parameters.put("type", type);

this.namedParameterJdbcTemplate.update(sql, parameters);

答案 1 :(得分:0)

您好,您可以单独检索fk,试试这个: 首先从location_type表中获取一个查询获取类型,然后尝试在主插入查询中插入您所获得的内容,如下所示:

String sqlForType = "SELECT id FROM location_type WHERE type =?";
String type = null;
 try {
            dbConnection = getDBConnection();
            PreparedStatement preparedStatement = dbConnection.prepareStatement(sqlForType);
            preparedStatement.setString(1, "main");
            // execute select SQL stetement
            ResultSet rs = preparedStatement.executeQuery();
            while (rs.next()) {type= rs.getString("type");}

然后按照您的工作代码将类型也添加到Insert查询和HashMap中,这将来自上面的查询结果:

// your previous working code
//and add this also in your HashMap
parameters.put("type", type);

this.namedParameterJdbcTemplate.update(sql,parameters);