Using Oracle Auto-Increment/Sequence in Hibernate/MyBatis

Categories: Java; Tagged with: ; @ May 1st, 2013 23:41

(Hibernate) Error 1 : java.sql.SQLSyntaxErrorException: ORA-02289: sequence does not exist

Solution:

Specify the sequence:

package com.liguoliang.jee.vo;

/**
 * Represents Client.
 * @author Guoliang
 *
 */
@Entity
@Table (name="Client")
public class Client {
	
	@Id
	@Column(name="id")
	@SequenceGenerator(name="my_seq", sequenceName="CLIENT_ID_SEQUENCE")
	@GeneratedValue(strategy = GenerationType.SEQUENCE ,generator="my_seq")
	private int id;
	
	@Column(name="name")
	String name;
	
	public Client() {
		// TODO Auto-generated constructor stub
	}
//....

}

(MyBatis) Error 2: java.sql.SQLException: Invalid column type: getInt not implemented for class oracle.jdbc.driver.T4CRowidAccessor

Code before change:

	/**
	 * insert new client.
	 * @param client
	 */
	
	@Insert("INSERT INTO CLIENT(name) VALUES (#{name})")
	@Options(useGeneratedKeys=true, keyProperty="id")
	void insert(Client client);

Solutions:

1. Directly Remove @Options(useGeneratedKeys=true, keyProperty=”id”)

2. Replace @Options with @SelectKey:

	/**
	 * insert new client.
	 * @param client
	 */
	
	@Insert("INSERT INTO CLIENT(name) VALUES (#{name})")
	@SelectKey(
			keyProperty = "id",
			before = true,
			resultType = Integer.class,
			statement={" select CLIENT_ID_SEQUENCE.nextval AS id from dual"}
			)
	void insert(Client client);



// Proudly powered by Apache, PHP, MySQL, WordPress, Bootstrap, etc,.