JPA: User-Entity contains another User-Entity - jpa

In my domain model i have a user entity, which contains another user (composite pattern). When i want to persist the user, i get an error which says something like "Data too long for column...". This happens because the contained user is tried to be stored as a BLOB. I want the ID of the contained user to be stored - not the whole object as a BLOB.
What kind of annotation must i user in the case? The cardinality is 1 : 0..1 - so a user can contain another user.
here is the code ...
#Entity
#Table(name="flex_app_user")
public class User implements Serializable {
private User client;
public User(){
}
#OneToOne
public User getClient() {
return client;
}
}
... and the problem resulted by a change in the datamodel. The correct annotation is OneToOne. And everything works fine.
kind regards,
Jochen

The annotation must be #OneToOne.

As you are using the composite pattern can you use (fetch=FetchType.LAZY) on the relation ship used?

Related

How to store polymorphic related models

I am working on a system that have lots of users each has his own information so I needed to create a model for each. On the other hand, all those users have a common user model where their credentials being collected form those requirements it was suitable to have a polymorphic relation between all user types and the user model i.e., coordinator as a model and the user as a model I did the following
class Coordinator extends Model
{
protected $fillable= ['userid', ...];
...
public function user()
{
return $this->morphOne(User::class, 'userable');
}
}
class User extends Model
{
...
public function userable()
{
return $this->morphTo();
}
}
class CreateUsersTable extends Migration
{
public function up()
{
$table->bigIncrements('id');
...
$table->morphs('userable');
}
}
class CreateCoordinatorsTable extends Migration
{
public function up()
{
$table->bigIncrements('coordid');
...
$table->foreign('userid')->references('ID')->on('wp_users')->onDelete('cascade');
}
}
After migration I noticed that columns userable_type and userable_id not allowing null. How come I create a coordinator entity with its associated user entity?
I got it after googling...
Laravel One to Many Polymorphic Relationship - Create Records
The idea is not as I thought at the beginning. When I used the $table->morphs('userable'); the user table had two columns, userable_id and userable_type, and each allows no null by default and by ORM convention and I was thinking that they consider the user table is the master and other tables (i.e., coordinator, educator, shipper etc.) each as the detail table. According to this initial wrong understanding I was adding a userid column at each table to store the related user id for each specific user type and I was wondering how I am going to save the user that needs the userable_id and userable_type to be filled by saving the specific user first to get its id that will be provided to the user's userable_id the case resembles a deadlock situation as each table needs a piece of information that will be known after storing data on each to be able to save data to each table, wired!!!.
However, when I read the article in the above link I figured that it considers the table in an opposite way, unlike my thinking was (i.e., coordinator, shipper, etc. are the masters and the user table is the detail). That is for guys who use the models directly but for those who use repository package it is a little bit tricky and you need to do an extra work...

Join and where clause using Criteria in Spring boot

I'm trying to achieve something which is easily doable using named query but i want to do this using criteria.
Below are my two tables.
Notification:
id
userId (foreign key to user)
Notification
Visible
User:
userId,
name,
address
No I want to fetch notifications corresponding to a user (user id given) which are visible (value set to 1)
One way to do it to fetch notifications from User and iterate them to see which notification is visible, but i dont want to do that, as that will unnecessarily pull lots of data from db.
What should be the best way to do it?
You can use Spring data jpa to achive this with ease
create an interface extending JPA repository as
#Repository
#RepositoryRestResource
public interface NotificationRepository extends JpaRepository<Notification,Long (datatype for primary key)> {
List<Notification> findByUseridAndVisible(Long userid,int visible);
}
Now you can create service class and directly use this method as
class service(){
#Autowired
NotificationRepository notificationrepository;
public void method(){
Long userid=85;
int visible=1;
List<Notification> getnotificationlist= notificationrepository.findByUseridAndVisible(userid,visible);
}
}
Hope this will help you .

Auto generating a String non-primary key value using jpa

Kindly help me to find out a solution to my problem.
I have a property of type String in my entity which is not primary key.
This would act as system generated unique profile id for users in my project.
I want to auto generate this value like a random string of particular size.
Could you please help me to arrive at a solution.
I have tried the #Generator and custom id generator class. but still null is getting inserted to the field in db.
I am using maria db.
Hi you can use the hibernate events.
#PostPersist Executed after the entity manager persist operation is actually executed or cascaded. This call is invoked after the database INSERT is executed.
Starting with Java 5, the UUID class provides a simple means for generating unique ids. The identifiers generated by UUID are actually universally unique identifiers.
Please follow the sample example.
public class TestModel {
#Column("column_name")
private String uid;
//setter and getter for uid
#PrePersist
protected void onCreate() {
// set the uid
setUid(java.util.UUID.randomUUID());
}
}
Please find the below link for more information on #PrePersist.
https://docs.jboss.org/hibernate/entitymanager/3.5/reference/en/html/listeners.html

How to add Foreign Key Properties subsequently to a Code First Model?

Given the Model:
Public Class Customer
Property Id() As Guid
Property FirstName() As String
Property MiddleName() As String
Property LastName() As String
Property Addresses() As ICollection(Of Address)
End Class
Public Class Address
Property Id() As Guid
Property Name() As String
Property Street() As String
Property City() As String
Property Zip() As String
Public Property Customer() As Customer
End Class
Entity Framework 6 Code First has created a column called Customer_Id in my table Addresses. Now, I'd like to add a Property Customer_Id to my class Address that represents the existing foreign key relation:
Public Class Address
Property Id() As Guid
Property Name() As String
Property Street() As String
Property City() As String
Property Zip() As String
Public Property Customer() As Customer
//Added
Public Property Customer_Id() As Guid
End Class
Unfortunately this results in an InvalidOperationException while creating the DbContext saying:
The model backing the 'DataContext' context has changed since the database was created.
I tried different property names (with and without underscore, different casing). But still no luck. So, what is the correct way to add those properties subsequently without the need for migrations? I assume it's possible, because the model does not really change, I am only changing from an implicit declaration of a property to an explicit...
Update:
The responses show me, that I did not explain the problem very well. After some more reading I found the correct names now: I have an application which is installed several times at customer locations (therefore dropping and recreating the database is no option). Currently, it depends on Entity Framework's Independent Associations, but I want to have the Foreign Key in my entity as well (this is no change to the model, the foreign key is already there, but does not exist as a property in my entity, since this is currently only relying on the IA instead). I did not manage to add it without EF thinking my Database is outdated.
for me two ways :
drop table __MigrationHistory : that is have the new model runs, but forget migration functionalities
create a new db by changing the connection string of the application. Replace old __MigrationHistory by __MigrationHistory of the newly created db
Never tested the second solution, but it should work.
Before using any solution:
backup you db.
Before using first solution: are you sure you will never need migration functionalities ?
This exception is because you change your model. You have to set migration strategy. Please look at:
http://msdn.microsoft.com/en-us/data/jj591621#enabling
(edited)
First of all you have to remove that exception. Even if you didn't add any new column to your database your model has changed because you added new property to Address class. If you check your DB you will find dbo.__MigrationHistory table with Model column. Last (earliest) value from that column is used for checking that your model and DB are compatible. I'm not sure but I think that EF stores there binary serialized model. So the solution is - recreate DB or add migration (probably empty migration).
(edited)
When you want to set FK you can do this very simple by Data Annotations
// c# example
public class Address
{
...
public string CustomerId { get; set; }
[ForeignKey("CustomerId")]
public Customer Customer { get; set; }
}
or in fluent api
// c# example
modelBuilder.Entity<Address>()
.HasRequired(arg => arg.Customer)
.WithMany()
.HasForeignKey(arg => arg.CustomerId);
or look at:
http://weblogs.asp.net/manavi/archive/2011/05/01/associations-in-ef-4-1-code-first-part-5-one-to-one-foreign-key-associations.aspx
http://msdn.microsoft.com/en-us/data/hh134698.aspx

How do I extend a dbcontext entity class?

I have exposed some EF5.0 entities generated from a database through at WCF data service.
The data service is consumed by a WPF-client which takes the entities (from the data service) and store them locally. I do this by creating a code-first entity database based on the WCF-entities:
public class LocalRaceContext : DbContext
{
public LocalRaceContext() { }
public LocalRaceContext(string connstr) : base(connstr) { }
public DbSet<Participant> Participants { get; set; }
.
.
. more ...
}
I want to extend the Participant with a new property (in the client-side model). I figured I could just do this with a partial class like so:
public partial class Participant
{
public virtual List<Stamp> Stamps { get; set; }
}
This however does not work. Do I need some kind of attribute on the partial class?
I get the following error:
"The type 'RaceEntities+Participant' was not mapped. Check that the type has not been explicitly excluded by using the Ignore method or NotMappedAttribute data annotation. Verify that the type was defined as a class, is not primitive, nested or generic, and does not inherit from EntityObject."
Edit:
#IronMan84: The original model (without the partial class) works because EF code-first takes care of the database and table creation. Actually it works perfectly fine and I am able to save the EF model in a local SQL CE file and retrieve the objects again as EF-classes later.
What I'm trying to achieve is to persist data from the data service locally but in a model which is somewhat extended. I've succeeded so far up until the extending part.
#Matt Whetton: It fails when I create a new instance of LocalRaceContext.
Edit2: I've tried to make an empty partial class (no properties). It still throws the same error.
Thanks in advance
Frederik
Nested classes are not yet supported by EF. Move the Participant class outside of RaceEntities.