I'm trying to create an H2 Trigger which should trigger before an Insert query is executed, because I need to set an ID in an SQL Table, which I need to create first in another table
The table where the insert should happen looks like this:
CREATE TABLE IF NOT EXISTS INGREDIENTS(
ID INT NOT NULL,
Name VARCHAR(50),
ALK INT check (ALK <= 100 and ALK >= 0),
CalPerHundred INT,
PRICE DOUBLE check(PRICE>=0),
FOREIGN KEY (ID) REFERENCES ITEM(ID)
);
Create for the Trigger:
CREATE TRIGGER IF NOT EXISTS ING_TRIGGER
BEFORE INSERT
ON INGREDIENTS
FOR EACH ROW
CALL "Partyplaner.Persistence.Trigger.IngredientsTrigger";
The code for the Trigger:
public class IngredientsTrigger implements Trigger {
private Logger LOGGER = LoggerFactory.getLogger(IngredientsTrigger.class);
@Override
public void init(Connection conn, String schemaName,
String triggerName, String tableName, boolean before, int type)
throws SQLException {
LOGGER.debug("hello im init");
}
@Override
public void fire(Connection conn, Object[] oldRow, Object[] newRow)throws SQLException {
LOGGER.debug("hello im fire");
PreparedStatement pstmt_key;
try {
pstmt_key = conn.prepareStatement("INSERT INTO ITEM () VALUES ()");
} catch (SQLException e) {
throw e;
}
pstmt_key.executeUpdate();
ResultSet generatedKeys = pstmt_key.getGeneratedKeys();
generatedKeys.next();
int id = generatedKeys.getInt(1);
generatedKeys.close();
newRow[0]=id;
}
@Override
public void close() throws SQLException {}
@Override
public void remove() throws SQLException {}
}
I can see the Trigger in the H2 WebInterface, but when I'm trying to Insert a Ingredient, I get an SQL error which says NULL is not allowed for ID; but that's exactly what the Trigger should do? I only see the init log message from the Trigger, so I'm relatively sure it doesn't get called, I checked the classpath in the create file like 5 Times, even let it print with Trigger.class.getName().
I'm using Maven and Spring, could it be that the Classpath has to be something else because of it?
Ok, the answer was pretty simple, i had to delete the NOT NULL Annotation from the Table now everything is working fine.