这里利用PostgreSQL扩展的JDBC方法进行数据库自定义类型和Java类的映射关系,将Java对象插入关系数据库中。
步骤如下:
1.在数据库中自定义数据类型(CREATE TYPE TypeName AS)
2.在Java中新建对应的JavaBean,继承PGobject类,实现Serializable接口。
3.将数据库连接对象Connection接口强制转换成PGConnection,添加数据类型映射
((PGConnection)connection).addDataType(TypeName, 类型对应JavaBean的类)
4.给JavaBean对象设置类型。利用setType方法,参数为数据库中的TypeName。
5.利用PreparedStatement的setObject方法设置。
下面给出实例代码:
自定义数据类型:
CREATE TYPE provider AS( name varchar(20), address varchar(20) );
public class Student extends PGObject implements Serializable { private String name; private String address; public Student() {} public Student(String name, String address) { this.name = name; this.address = address; } public void setName(String name) { this.name = name; } public String getName() { return name; } public void setAddress(String address) { this.address = address; } public void getAddress() { return address; } }
try { String sqlStr = "INSERT INTO goods(id, name, price, type, provider) VALUES(?, ?, ?, ?, ?)"; ((PGConnection)dbConnection).addDataType("provider", Provider.class); PreparedStatement pStatement = dbConnection.prepareStatement(sqlStr); pStatement.setInt(1, goods.getId()); pStatement.setString(2, goods.getName()); pStatement.setBigDecimal(3, goods.getPrice()); pStatement.setString(4, goods.getType()); goods.getProvider().setType("provider"); pStatement.setString(5, goods.getProvider()); pStatement.execute(); pStatement.close(); } catch (Exception e) { e.printStackTrace(); }
搞了两天终于搞定了!有遇到类似问题的童鞋可以参考!