Spring jpa column defaultvalue - spring

I'm trying to do the following
#ManyToOne
#JoinColumn(name="tier_id", columnDefinition = "INT default 1", nullable = false)
public Tier getTier() {
return tier;
}
but while inserting the record I get
com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Column 'tier_id' cannot be null
I want default tier_id to be 1 if it's not set, but it's not working. How can I correctly set this up?

The default SQL value is only used if the column is not present at all in the insert statement.
But Hibernate doesn't omit columns in insert statements. If you create an entity instance with a null tier, and persist it, you're effectively saying Hibernate that you want to persist an entity with a null tier, and Hibernate explicitely sets the tier_id column to null, since that's what you told it to do.
So, if you want your entity's tier to be the tier with ID 1, then do it explicitely in your application code:
SomeEntity e = new SomeEntity();
e.setTier(em.getReference(Tier.class, 1));
em.persist(e);

Related

Check ManyToOne eager and lazy relations for null

Suppose that a certain booking's invoice is null in the DB.
public class Booking {
#Id
private Integer id;
...
#ManyToOne(... fetch = FetchType.LAZY)
#JoinColumn(...)
private Invoice invoice;
}
It seems that a many-to-one lazy relation always creates a proxy object for booking.getInvoice(), while an eager relation would just return a null. I think I can check the booking.getInvoice().getId(), but for that I must be sure that the relation is lazy. I don't want to do that because it forces me to always track the relation fetch type in the client code.
What if I have a lot of existing code that checks null in 'eager mode' and I want to convert a certain relation to lazy? Do I have to convert all null checks for that relation as well?
I'd think that since the DB field is null then the JPA would be smart enough to not create the proxy object at all here, leaving the private field invoice null.
Is the double check for null and id the only way to go?
Invoice invoice = booking.getInvoice();
if (invoice != null && invoice.getId() > 0) {
...
}
Is there a fetch-type-independent way to check for null many-to-one children in JPA?

How to retrieve an Entity Object just with #Id (Proxy object), check if it exists and assign it to a #ManyToOne association

I have an entity Product which have many fields and associations (around 60).
And a table ProductView which has a #ManyToOne(fetch = FetchType.LAZY) association with Product.
Is there a optimal way to retrieve Product object and assign it to ProductView ?
If its used JPA findById(productId) or JPQL/EntityManager selects-> It will retrieve all products fields and associations
Product product = productRepository.findById(productId);
ProductView productView = new ProductView(product);
save(productView);
If its used JPA getOne -> It solves the problem but the Proxy can throw error if Product does not exists. And this error can not be handled because it happens at runtime.
Product product = productRepository.getOne(productId);
ProductView productView = new ProductView(product);
save(productView);
If a DTO is used or Interface which refers to the same Product Table -> We will get just an object with Id field, but a lot more processes will need to be added (Which I am not familiar with)
Delete foreign keys from ProductView table (#ManyToOne -> #Column) and simple assign productIds. But in this way, there will be no logic connection between tables.
ProductView DB
How usually developers avoid this problem ?
I don't understand what the problem is. Just use getOne approach and at the end of your method, use flush which will throw the constraint violation exception that you can handle. This is the way to go.

How to fetch jsonb column through jpa springboot?

I have one table which contains one column 'details' as jsonb data type. The content is
{
"name": "username",
"value": "user1",
"is_required": true
}
for one row.
I want to write one jpa hibernate query in spring boot to fetch this record when name == username for details column.
Something like this:
select details->>'value' from table where details->>'name' = 'username';
This syntax does not work in spring boot hibernate query.
I got the answer. Use
#Query(value="select details->>'value' from table where details->>'name' = 'username'", nativeQuery=true)

weblogic + eclipselink + 2 different thread = lazyloading don`t work

I have two threads one of them write text field to the database, another try to read this field but it can`t.
field has following anatation:
#Lob
#Column(name = "response_soap")
#Basic(fetch = FetchType.LAZY)
public String getResponseSoap() {
return responseSoap;
}
Both thread it's part of the web application. Both running on the same weblogic server.
All transaction is commited. There is field in the database.
Every time I'm creating new Entity manager.
What error do you get?
Try using a refresh, em.refresh(object)
Are you serializing the object? Since it is LAZY it will be null when you serialize it, unless you access before you serialize it. Try making it EAGER.
I believe that only
Many-to_many and One-to-many are can be set to lazyload
One-to-one, Many-to-one and Basic are all Egar
http://wiki.eclipse.org/EclipseLink/UserGuide/JPA/Basic_JPA_Development/Mapping/Basic_Mappings/Lazy_Basics

How to assign null to sql entity columns

I have generated linq to sql entites but cannot figure out how to assign null to a nullable column. whenever i try to assign null to it it says "there is no implicit type conversion between int and ". BTW the type of the field is int? and the database column is also nullable.
Try to assign it System.DBNull instead
It seems as though the column isn't really nullable. Check the properties of the column and see that it really is marked as nullable. If it isn't, check your database model and try to recreate the LINQ to SQL model if it's nullable in the database.
Mind that you can't simply mark it as nullable in the LINQ to SQL model and not in the database, since these kinds of discrepancies may cause your LINQ to SQL model to stop working.
Post edit update: I can see that the field type is int? which is the same as Nullable<int> so there shouldn't be a problem to set it to null. However, when getting the integer value, you should use the Value property of the int?. Is that the problem?
Usually I've had to use DBNULL.Value when assigning or comparing a database value to null.
You only need to assign then entites nullable property to null. I've never had to assign or test against System.DBNull when using linq-to-sql entities.
It sounds like the generated entity classes have been manually modified or are out of date from the database.
For your reference, the following is a nullable and a non-nullable integer field:
private int? _someID;
/// <summary>
/// Gets or sets the SomeID.
/// </summary>
[Column(Name="SomeID", Storage="_someID", DbType="INT", UpdateCheck=UpdateCheck.Never)]
public int? SomeID
{
private int _someOtherID;
/// <summary>
/// Gets or sets the SomeOtherID.
/// </summary>
[Column(Name="SomeOtherID", Storage="_someOtherID", DbType="INT NOT NULL", CanBeNull=false, UpdateCheck=UpdateCheck.Never)]
public int SomeOtherID
{
Check your generated entity looks something like the above.
You wrote 'the type of the field is int?'.
I guess this is the problem: the type of the field should be int (without the ?), and the property 'allow null value' should be set to true.
In the designer you can change the field type to int? instead of int and 'allow null', but you run into all kind of trouble this way (as you might have noticed).
It is when you're trying to explicitly create a DB set with a nullable column in an entity.
new Nullable() is what you're looking for.
someEntity newEntity = new someEntity()
{
aNullableInt = new Nullable<Int32>()
};

Resources