I would like to create an object in MS SQL with hibernate, name of this table is "user". it does not work!.
I think this problem may caused by name of table/entity, user is keyword.
what should I do to have table with name "user"?
#Entity
#Table(name = "user")
public class User {
Enclose the table name in square braces:
#Entity
#Table(name = "[user]")
public class User {
That way Hibernate will escape it when it creates the table. If you put all your field and table names in square braces as a rule, you never have to consider the underlying DBMS when setting up your mappings.
<rant>It always bothered me that you had to do this. One of the major goals of Hibernate is to isolate your code from the underlying database -- I never understood why the dialect implementations don't properly handle escaping reserved keywords.</rant>
See also: Using database reserved keywords in Hibernate
I should use grave accent (`). for use keyword in hibernate we have to use (`) around keyword.
#Entity
#Table(name = "`user`")
public class CompanyUser extends
Related
I am generating MySQL table by Hibernate as follows:-
#Entity
#Table(name = "buyerPartyDetails")
public class BuyerPartyDetails {
.......
}
But in MySQL the actual table name is as buyerpartydetails I was expecting it should be buyerPartyDetails. How do I force hibernte to genarate table name as my espection?
You can force Hibernate to quote the identifiers by setting:
hibernate.globally_quoted_identifiers=true
or
hibernate.globally_quoted_identifiers_skip_column_definitions=true
which will generate quoted table names in DDL. It might however require SET GLOBAL SQL_MODE=ANSI_QUOTES; as by default MySQL uses backticks ` to quote the names.
I'd like JPA EclipseLink creates tables exactly as is the ClassName (and fields) WITHOUT annotation #Table and #Column. It's always creates tables and fields with UPPERCASE, which makes readability difficult in the DB console.
ex.:
#Entity
public class ChannelEntity {
#Id #GeneratedValue
public Long id;
public String name;
public String description;
public Boolean oficial;
#Temporal(TemporalType.TIMESTAMP)
public Date creation;
}
And I'd like results in
Table: ChannelEntity
id creation description name oficial
----------------------------------------------------
351 NULL meu desc meu nome 1
Maybe exist same parameter in persistence.xml, but I can't find it.
If EclipseLink behaves correctly, the parameter you are looking for is delimited-identifers. From the JPA 2.1 spec:
It is possible to specify that all database identifiers in use for a
persistence unit be treated as delimited identifiers by specifying the
<delimited-identifiers/> element within the persistence-unit-defaults
element of the object/relational xml mapping file. If the
<delimited-identifiers/> element is specified, it cannot be
overridden.
If this element is included, EclipseLink should delimit all database identifiers in its generated SQL, which would cause the database objects to be created with case-sensitive names.
I was trying to find an answer but, unfortunately, with no luck.
The data structure looks like this:
TABLE_X - contains userId, also userType telling if this is external or internal user
INTERNAL_USERS - contains key userId
EXTERNAL_USERS - also contains key userId
TABLE_X.userId is either INTERNAL_USERS.userId or EXTERNAL_USERS.userId.
Now, I would like to map an entity out of TABLE_X and have user object mapped to correct entity, either INTERNAL_USERS or EXTERNAL_USERS.
How should I do this?
Should I create two fields and map one to INTERNAL_USERS and one two EXTERNAL_USERS and just see which one is not empty?
If I understand correctly your question, what you have to do is to replicate structure of the TABLE_X columns with fields on the TABLE_X class, and add to fields one for INTERNAL_USERS.userID and one for EXTERNAL_USERS.userID
But if you store on TABLE_X.userType if a user is internal or external, I think that the best thing you can do is not create any other table, because you just have the information you need on your first table (TABLE_X). If you want to know all the users that are internal for instance, just do a SQL and select all the values from TABLE_X where userType = "Internal"
Use Hibernate inheritance. Check out the Table per class inheritance pattern. Here you have both INTERNAL_USERS or EXTERNAL_USERS data in TABLE_X with userType as the discriminator column.
http://docs.jboss.org/hibernate/stable/annotations/reference/en/html_single/#d0e1191
Given the table structure, you can use JPA Inheritance as detailed here:
https://en.wikibooks.org/wiki/Java_Persistence/Inheritance#Example_joined_inheritance_annotations
In Hibernate you can model such relationships as follows. When querying for a User you can then rely on Hibernate to return an instance of the correct type.
#Entity
#Inheritance(strategy=InheritanceType.JOINED)
public class User{
#Id
private Long userId;
}
#Entity
public class InternalUser extends User{
}
#Entity
public class ExternalUser extends User{
}
As noted in the article linked to, Hibernate does not require a discriminator column to be specified when using joined inheritance. It does however support a discriminator column if one is available. As you have one available in your schema - userType - then you could explicitly specify it if you wish. I imagine this would yield some performance benefit in terms of the generated SQL:
Mappings with optional discriminator column:
#Entity
#Inheritance(strategy=InheritanceType.JOINED)
#DiscriminatorColumn(name="userType")
public class User{
#Id
private Long userId;
}
#Entity
#DiscriminatorValue("INT")
public class InternalUser extends User{
}
#Entity
#DiscriminatorValue("EXT")
public class ExternalUser extends User{
}
I'm developing a code generator that have to generate JPA entities from database meta-model files. These model are from home-brewed modeling system which are being used to generate models other than JPA entities.
In these models some fields are mapping back to same database column. But it seems like JPA does not like that very much. When I try to run generated code I get
Exception [EclipseLink-48] (Eclipse Persistence Services - 2.6.0.v20140809-296a69f): org.eclipse.persistence.exceptions.DescriptorException
Exception Description: Multiple writable mappings exist for the field [FACT_INVENT_TRANS_HIST_DM.TRANSACTION_ID]. Only one may be defined as writable, all others must be specified read-only.
Mapping: org.eclipse.persistence.mappings.DirectToFieldMapping[TransactionIdKey-->FACT_INVENT_TRANS_HIST_DM.TRANSACTION_ID]
Descriptor: RelationalDescriptor(InventTransHistFactDM --> [DatabaseTable(FACT_INVENT_TRANS_HIST_DM)])
As I can't change the models only option left is to make one of those fields read-only. And the JPA entities being generated are only used to read data from database it will not used for writing data. Is there a way to mark some fields as read only or tell EclipseLink that these entities are read only so it does not have to worry about the multiple writable mapping.
I tried using EclipseLink's #ReadOnly annotation in all entities but it did not help this issue.
There is no #ReadOnly in JPA.
There are however attributes "insertable"/"updatable" that you can set against a field via #Column to effectively do the same.
The question may be almost 6 years old, but it's still being found today, so I'd like to address another option:
public class Foobar {
#OneToOne
#JoinColumn(name="SELF_COLUMN_FOO", referencedColumnName = "FOREIGN_COLUMN_TO_JOIN")
public Foo foo;
#OneToOne
#JoinColumn(name="SELF_COLUMN_BAR", referencedColumnName = "FOREIGN_COLUMN_TO_JOIN")
public Bar bar;
}
This can be used where SELF_COLUMN is obviously the relevant column in the Foobar table, and FOREIGN_COLUMN_TO_JOIN would be single key in the other table you wish to join.
This will be useful where you want to have two (or more) attributes in a single class, but only one column to join on the foreign DB table. For example: An Employee may have a home phone number, cell number, and a work phone number. All are mapped to different attributes in the class, but on the database there's a single table of phone numbers and id's, and an identifier column, say VARCHAR(1) with 'H' or 'W' or 'C'. The real example would then be...
Tables:
PHONENUMBERS
PHONENUMBER_ID,
ACTUAL_NUMBER
EMPLOYEE
ID
HOMENUMBER VARCHAR(12),
CELLNUMBER VARCHAR(12),
WORKNUMBER VARCHAR(12)
public class Employee {
#OneToOne
#JoinColumn(name="HOMENUMBER", referencedColumnName = "PHONENUMBER_ID")
public Phone homeNum;
#OneToOne
#JoinColumn(name="CELLNUMBER", referencedColumnName = "PHONENUMBER_ID")
public Phone cellNum;
#OneToOne
#JoinColumn(name="WORKNUMBER", referencedColumnName = "PHONENUMBER_ID")
public Phone workNum;
}
As you can see, this would require multiple columns on the Entity's table, but allows you to reference a foreign key multiple times without throwing the 'Multiple writable mappings exist...' that you showed above. Not a perfect solve, but helpful for those encountering the same problem.
I have some tables in db(postgresql) with names like this "Test".When i try create java classes from this tables with hibernate its not happening. I get classes from tables with names like this test. How to make hibernate can see tables with quotes in names?
UPDATE
Maybe i write question not correct. But i cant create java classes and i want to know how to do reverse ingenering with tables which have names in qoutes. I cant delete qoutes from table names and column names couse they have names like Type and Full.
By default, Hibernate assumes the database table name is the same as the class name, but you can override this behaviour via the #Table annotation:
#Entity
#Table(name="\"Test\"") // Will use "Test" (including the quotes) as the table name
public class Test {
The #Table annotation is used to specify the table to persist the data. The name attribute refers to the table name. If #Table annotation is not specified then Hibernate will by default use the class name as the table name. So your database's table name is "Test" then you should use your class name is "Test".
Please check your database with
select * from """Test""" if your table name is "Test".
Your entity class should be
#Entity
#Table(name = "\"\"\"Test\"\"\"")
public class Test {
}
It seems that you are not using annotations as of now...
So in case you want to use "Test" as table name you should define the mapping of POJO with your table either via annotations as defined by Bohemian
#Entity
#Table(name="\"Test\"")
public class Test {
or define in the Test.hbm.xml in which you have to map your table and fields to java class and columns.
Alternately, you can specify the schema and database name inside #Table annotation.
#Entity
#Table(name = "Test", schema = "public", catalog = "TestDatabase")
Hibernate will recognize the table without the need to escape double quotes.