How to create a @Onetomany relationship in JPA, in 3 tables that already exist in the database?

Asked

Viewed 721 times

1

I want to create a relationship @OneToMany in JPA using 3 tables I have already created in my database (I don’t want it to create the tables for me), the tables are Usuario, Perfil and UsuarioPerfil. for this I am using the following code snippet in my User class.

@OneToMany(fetch = FetchType.EAGER)
List<Perfil> perfisPermitidos = new ArrayList<Perfil>();

The problem is when running the code the following Exception is launched

com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 
'nomedomeubanco.Usuario_Perfil' doesn't exist

I know he does this because JPA tries to create the User_profile table automatically to use as an intermediate table, but I want him to use my table UsuarioPerfil which already exists in my bank for exactly that purpose.

So that being said my question is how do JPA map the table UsuarioPerfil as relationship table and do not try to create a default table which in this case is the table Usuario_Perfil?

  • In order not to create the tables you have to put ddl-auto=None and create the tables manually or in some other way, using liquibase for example. About relationships see https://answall.com/a/234768/113075 this answer is very well made

1 answer

1


  • Yes, but what I need is the opposite, at the time of creating the relationship I want it to Mapeie and use tables I already have created in the bank, In my case in specific It maps Perfil and Usuario very well, the problem is that it tries to create a table Usuario_perfl, because of its conventions, instead of using my table Usuarioperfil, so I need to make him understand that he has to use my table and not try to create his. NOTE: I disabled automatic table creation in settings.

  • Got it, you need to use a @Jointable annotation.

  • Check the link if you are https://stackoverflow.com/questions/1378248/one-to-many-relationship-with-join-tablehttps://stackoverflow.com/questions/1378248/one-to-Many-Relationship-with-Join-table!

  • Yes, it was @Jointable that I needed.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.