Spring GeneratedKeyHolder example

      Click here to attend Spring Framework 4.x and certification course with a discount

public int insertUser(final User u) {
        final String SQL = "INSERT INTO kameroom.user (" +
        		"firstname,lastname,password,email,dob,mobile1,mobile2,homephone,gender," +
                + " values(?,?,?,?,?,?,?,?,?,?,NOW(),?,?,?,?,NOW(),?,?)";
        KeyHolder keyHolder = new GeneratedKeyHolder();
                new PreparedStatementCreator() {
                    public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
                        PreparedStatement ps =connection.prepareStatement(SQL);
                        ps.setString(1, u.getEmail()); //username
                        ps.setString(2, u.getFirstname()); //firstname
                        ps.setString(3, u.getLastname(); //lastname                                       
                        ps.setString(4, u.getPassword()); //password
                        ps.setString(5, u.getEmail()); //email
                        ps.setDate(6, new java.sql.Date(System.currentTimeMillis())); //dob
                        ps.setString(7, u.getMobile1()); //mobile1 
                        ps.setString(8, u.getMobile2()); //mobile2
                        ps.setString(9, u.getHomephone()); //homephone
                        ps.setString(10, String.valueOf(u.getGender())); //gender            
                        ps.setInt(11,  Integer.valueOf(u.getEducation())); //occupation
                        //ps.setDate(13, new java.sql.Date(System.currentTimeMillis())); //membersince
                        ps.setString(12, u.getPhotopath()); //photopath
                        ps.setString(13, "1"); //status //1:looking for room?
                        ps.setBoolean(14, u.isSmoker()); //issmoker
                        ps.setBoolean(15, u.isHaspets()); //haspets
                        //ps.setDate(16, new java.sql.Date(new java.util.Date().getTime())); //datemodified
                        ps.setString(16, u.getInterests()); //interests
                        ps.setString(17, u.getDescription()); //description
                        return ps;
        return keyHolder.getKey().intValue();


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s