How to insert default value in JPA? - jpa

I would like to save a default value in a column when creating and updating with JPA, I tried it in the database and in java but it is not registered. IDE: NetBeans8.2 BD:Oracle11g
enter image description here
enter image description here

Why don't you just set the field in your entity to the default value?
#Entity
public class X {
private static final String DEFAULT_EST_ALQ = "A"
#Column(name = "EST_ALQ")
private String estAlq = DEFAULT_EST_ALQ;
public setEstAlg(String estAlg) {
// overwrite default value
}
}
Afaik the columnDescription is only used when generating tables from entities, e.g.
<property name="javax.persistence.schema-generation.database.action" value="create"/>
in persistence.xml
If you create the table via SQL the default value should be considered.
CREATE TABLE X(
EST_ALQ CHAR(1 CHAR) DEFAULT 'A'
)

Related

#Audited table and byte[] #Lob field problem

I have adudited table with #Lob field. Without #Audited saving object by Spring CrudRepository works ok, but when i want audit turn on i get error: PSQLException: ERROR: column "content" is of type oid but expression is of type bytea. How to resolve this ? Content column in PostgreSQL database is oid type (for both tables). On Hibernate 5.x the same configuration works, but not o Hibernate 6.x.
#Entity
#Audited
#Table(name = "up_test")
#Getter #Setter
public class UploadTestEntity extends BaseEntity {
#Id
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "up_test_seq")
#TableGenerator(table = "id_generator", name = "up_test_seq", initialValue = 1, allocationSize = 1)
private Integer id;
#Lob
private byte[] content;
}
Just remove the #Lob annotation.
The Postgres JDBC driver does not support handling the bytea type via the JDBC LOB APIs setBlob()/getBlob(). I don't know why, and it seems like something that should be supported.
But on the other hand, you don't need it here. The most natural way to handle a field of type byte[] mapping to bytea is to use setBytes()/getBytes(), which is the job of Hibernate's VarbinaryJdbcType.
I don't know where people got the idea that they needed to use #Lob for this instead of just going with the default mapping for byte[].

JPA Repository findByEnum does not cast the Argument Enum to String or Postgres Cast not working as expected

I have a Spring Boot (2.5.4) backend pointing to a Postgres (9.6) database. I have an entity in Spring that makes use of the #Enumerated(EnumType.String) annotation on a field of an Enum type. Persisting this entity works as expected and converts the Enum into a String. In Postgres, I have the respective enum casted to character varying. Things are working to this point except invoking a custom findBy "Enum" method in the JPA Repository interface. Now in Spring and Postgres I have defined the following:
Enum:
public enum EnumExampleType {
TYPE1, TYPE2
}
Entity:
#Entity
#Table(name = "enumexampletable")
#Data
#NoArgsConstructor
public class EnumExampleTable {
#Id #GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name = "enum_example_table_id", columnDefinition="serial primary key")
private int enumExampleTableId;
#Column(unique = true, name="enum_example_type")
#Enumerated(EnumType.STRING)
public EnumExampleType enumExampleType;
}
Repo:
public interface EnumExampleTableRepo extends JpaRepository<EnumExampleTable, Integer> {
EnumExampleTable findByEnumExampleType(EnumExampleType enumExampleType);
}
Working Code as Expected
EnumExampleTable ex1 = new EnumExampleTable();
EnumExampleTable ex2 = new EnumExampleTable();
ex1.setEnumExampleType(EnumExampleType.TYPE1);
ex2.setEnumExampleType(EnumExampleType.TYPE2);
enumExampleTableRepo.save(ex1);
enumExampleTableRepo.save(ex2);
RestController: (to invoke) (not working)
#Autowired
EnumExampleTableRepo enumExampleTableRepo;
#GetMapping("/findByTest")
public EnumExampleTable enumTest() {
return enumExampleTableRepo.findByEnumExampleType(EnumExampleType.TYPE1);
}
When calling this code the following error is received:
Blockquote org.postgresql.util.PSQLException: ERROR: operator does not exist: enumexampletype = character varying
Hint: No operator matches the given name and argument type(s). You might need to add explicit type casts.
Postgres Database:
drop table if exists enumexampletable;
drop type if exists enumexampletype cascade;
drop cast if exists (character varying as enumexampletype);
create type enumexampletype as enum('TYPE1', 'TYPE2');
CREATE CAST (character varying as enumexampletype) with inout as implicit;
create table enumexampletable (
enum_example_table_id serial primary key,
enum_example_type enumexampletype
);
This suggests to me that either:
A: The findByEnumExampleType method does not convert the enum to a string
B: Postgres does not invoke this cast in this particular call
Also to Note: (A hard coded native query will function properly, but this is not the dynamic functionality I need)
#Query(value="select * from enumexampletable e where e.emum_example_type = 'TYPE1'", nativeQuery=true)
EnumExampleTable testNQ();
Thoughts or suggestions?

How can I set the action "on delete set null" to a foreign key with JPA

In my entity class I have a column defined like this:
#ManyToOne(fetch=FetchType.LAZY)
#JoinColumn(name="foo_id", nullable=true, updatable=true, foreignKey=#ForeignKey(name="fk_foo_fee"))
private Foo foo;
Today I checked the properties of the foreign key fk_foo_fee on pgAdmin and found out that its action is on delete no action. The problem is that the action must be on delete set null. pgAdmin doesn't let me change it with its interface. So how can I change it with JPA?
You can try this:
child.setParent(null);
session.delete(parent);
You should also be able to put it in a PreRemove:
#PreRemove
private void preRemove() {
// set foo to null here
}

Postgres insert record with Sequence generates error - org.postgresql.util.PSQLException: ERROR: relation "dual" does not exist

I am new to Postgres database.
I have a Java Entity class with the below column for ID:
#Entity
#Table(name = "THE_RULES")
public class TheRulesEntity {
/** The id. */
#Column(name = "TEST_NO", precision = 8)
#SequenceGenerator(name = "test_no_seq", sequenceName = "TEST_NO_SEQ")
#GeneratedValue(generator = "test_no_seq", strategy = GenerationType.AUTO)
#Id
private Long id;
/** The test val. */
#Column(name = "TEST_VAL", nullable = false, length = 3)
private String testVal;
Code:
rulesRepository.saveAndFlush(theRulesEntity)
Table:
CREATE TABLE THE_RULES
(
TEST_NO INT NOT NULL,
TEST_VAL VARCHAR(3) NOT NULL
)
CREATE SEQUENCE "TEST_NO_SEQ" START WITH 1000 INCREMENT BY 1;
When I try to insert a new record into the postgres database from my application (the ID value is null in Java code during Debug mode), then I get the below error:
Caused by: org.postgresql.util.PSQLException: ERROR: relation "dual" does not exist
But If I insert the record manually into database table and then update the record from my application, then the record is updated successfully (Probably because the application uses the same ID value so no need to refer to the Sequence TEST_NO_SEQ value anymore)
Looks like the database is not able to access the sequence from dual table.
Could anyone help me how to fix this?
Thanks.
Thanks to Joop and a_horse_with_no_name, the issue is resolved
I have used Oracle driver which is wrong. I have updated my code to use Postgres driver
I created the Sequence again in the database with same name but without the Quotes
I used all capital-case letters in my Java entity class to refer to the sequence correctly

Spring MVC <form:options> selected value

I got relation "Many to one" between my CPVCode adn OrderType:
public class CPVCode {
#Id
#GeneratedValue
private int id;
private String cpv_code;
private String description;
#ManyToOne
#JoinColumn(name="id_parent")
private OrderType orderType;
//getters na setters: ...
}
Everything works well, but I NEED to displays selected value in my form:
<form:select path="orderType" items="${orderTypes }" itemLabel="title" itemValue="id" ></form:select>
It seems to work almost good: It displays list of all OrderTypes ( by ${orderTypes} which returns array of that objects type), it saves proper values by Hibernate, BUT thereis no way to select current value of orderType after refreshing...
your passing a list to a selectbox, so it iterates over the list. You need to change which bean the selectbox references - a single value oderType from CPVcode.
And also possibly change the selectbox to a different html form element ?