UNIQUE KEY generated from nowhere - mysql

I have 2 tables with #ManyToMany relation field. In hibernate cfg i have
<property name="hbm2ddl.auto">update</property>
Table which is created during application startup has UNIQUE key set on PartId column, which is
#JoinColumn(name="PartId")}
in #ManyToMany relation. I didn't set anywhere that this column should have unique key. Is this the default auto creation behaviour?
The DB is MySQL 5.5
Thanks.
UPD:
Full field desc is:
#ManyToMany
#JoinTable(name="Part_Dev",
joinColumns={#JoinColumn(name="PartId")},
inverseJoinColumns= {#JoinColumn(name="DevCode")})
public List<Dom> getDom() { return dom; }
UPD 2
sorry, I see I didn't mention it. Unique key in Parts table,
#Entity #Table(name="Parts")
public class Parts implements Serializable{
#ManyToMany
#JoinTable(name="Part_Dev",
joinColumns={#JoinColumn(name="PartId")},
inverseJoinColumns= {#JoinColumn(name="DevCode")})
public List<Dom> getDom() {
return dom; }
#Column(name="PartId")
public Integer getPartId() {
return partId; }

you need to specify #JoinTable to make it happen. For instance, if you have two entities : Employee and Project in a many-to-many relationship. You need to have #JoinTable on one side.
#Entity
public class Employee {
#Id private int id;
private String name;
#ManyToMany
#JoinTable(name="EMP_PROJ",
joinColumns=#JoinColumn(name="EMP_ID"),
inverseJoinColumns=#JoinColumn(name="PROJ_ID"))
private Collection<Project> projects;

So, as Chris told, that was the way to identify each part.

Related

How to store value objects in relational database like mysql

I have a scenario where I have the user table and the address table. The address table is a value objects in domain driven design in my understanding. How do I store value objects in mysql database? this sounds a bit confusing but I couldn't understand this idea value objects are immutable but how to store them?
Below are classes of my two entity
user.java
#Getter #Setter #NoArgsConstructor
#Entity // This tells Hibernate to make a table out of this class
#Table(name="user")
public class User {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#JsonProperty("userid")
#Column(name="userid")
private Long user_id;
#JsonProperty("user_nome")
private String nome;
#JsonProperty("user_email")
#Column(unique = true, nullable = false)
private String email;
#JsonProperty("user_cpf")
private String cpf;
#JsonProperty("user_telefone")
private String telefone;
#JsonProperty("user_celular")
private String celular;
#JsonProperty("user_senha")
private String senha;
#Column(name="createdAt", columnDefinition="TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP")
#Temporal(TemporalType.TIMESTAMP)
#JsonProperty("user_createdAt")
private Date createdAt;
#Column(name="updateAt", columnDefinition="TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP")
#Temporal(TemporalType.TIMESTAMP)
#JsonProperty("user_updateAt")
private Date updateAt;
/*Person p1 = new Person("Tom", "Smith");
p1.setId(1L);
p1.setStartDate(new Date(System.currentTimeMillis())); */
}
class Address:
#Getter #Setter #NoArgsConstructor
#Entity // This tells Hibernate to make a table out of this class
#Table(name="address")
public class Address {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#JsonProperty("address_id")
private Long address_id;
#JsonProperty("address_endereco")
private String endereco;
#JsonProperty("address_bairro")
private String bairro;
#JsonProperty("address_numero")
private String numero;
#JsonProperty("address_complemento")
private String complemento;
#JsonProperty("address_cidade")
private String cidade;
#OneToOne(fetch=FetchType.LAZY)
#JoinColumn(name = "userid")
private User userid;
}
Basically however you want: you could enforce immutability in the database, but you don't have to. Immutability can be enforced in the database by creating an unique constraint on a combination of values of an address, zipcode + house number for example.
As a database administrator I personally don't like developers enforcing immutability in the database because I see implementing/enforcing business logic in the database as a category error. What is an immutable value within the domain, to me is just data that needs to be consistently stored. Database rules are meant to ensure data consistency and the added complexity of implementing immutability in the database can interfere with that. Lets do a thought experiment:
You ensure that an address value is unique in the database with a constraint that covers all properties and store your data. Some time later a customer places an order that happens to have the same address, but he lives on the North Pole. The order is saved but the address isn't because my server throws an error because the address violates the constraint because it already exsists in the US, but that's not saved/part of the constraint. Now I have a problem because that orphaned order violates the data model, you complain to me because my server threw an error and now it's up to me to figure out what's wrong with your design decision to apply the abstract concept of immutability outside your domain, and have to update the data definition in a production environment in order to fix it.
So I think it's best you acknowledge that by storing data it leaves your domain and that is a risk your design should take into account. What I'd advice (or silently implement haha) would be the addition of an ID within the table and a record versions of the same 'immutable value' for tracability, consistency and agility to react to unforseen circumstances. Just like with user and transaction entities ;)

Remove Duplicate entry '59' for key 'PRIMARY in Hibernate

I am very new in Hibernate. I am using Hibernate with JPA. I have an annotated entity class and a table related to that entity class.
#Entity
public class Test implements Serializable {
#Id
#GenericGenerator(name="inc" , strategy="identity")
#GeneratedValue(generator="inc")
private int id;
private String address; // setter getter and constructor
}
When saving this entity, it insert the data into the db. But during application running process another application is inserting data into same table. when my application try to save the data then Duplicate entry '59' for key 'PRIMARY' exception generated. So I want to use a generator which can insert the data and generate id in database level rather than application level and the identifier must saved back to my entity.
Use the Table generator strategy or the sequence generator.
You do not have to specify a generator. You can use the default generator and never set the id manually. If the error still comes post your merge/persist method.
More informations about generators can you found here https://en.wikibooks.org/wiki/Java_Persistence/Identity_and_Sequencing
#Entity
public class Test implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String address; // setter getter and constructor
}

MySQL/JPA : How create a correclty relation and cascade?

I was very impress with my project, but suddenly I notice that I am doing something very wrong, 'cause, every create, merge, delete I was doing manually, but I should let the JPA take care of that for me right ?
What I do, is create the database then create the entities from it. So here is my database so you guys can understand my concept issue.
In a simple way:
An user has an address, only one address. This address is composed by city, state and country. I want to be able to create, update the user address by cascade.
I think my mapping, generated by JPA is wrong (or my understaing is wrong), let me show it:
public class User {
..
//bi-directional many-to-one association to UserAddress
#ManyToOne(cascade = CascadeType.ALL) // should be one to one ?
#JoinColumn(name="id_user_address")
private UserAddress userAddress;
..
}
public class UserAddress {
..
//bi-directional many-to-one association to User
#OneToMany(mappedBy="userAddress", fetch=FetchType.EAGER)
private List<User> users;
//bi-directional many-to-one association to AddressCity
#ManyToOne
#JoinColumn(name="id_city")
private AddressCity addressCity;
//bi-directional many-to-one association to AddressState
#ManyToOne
#JoinColumn(name="id_state")
private AddressState addressState;
//bi-directional many-to-one association to AddressCountry
#ManyToOne
#JoinColumn(name="id_country")
private AddressCountry addressCountry;
..
}
What I think is that the user has one adress only, so it should be OneToOne mapping ?
And the same goes for UserAdress about country, state and city.
If you want to allow multiple users on the same address #ManyToOne is what you want. If you use #OneToOne you can have only one user per address.

Persisting a Many-to-Many entity by adding to a List of entities

I am getting a list of entities and attempting to add more values to it and have them persist to the data base... I am running into some issues doing this... Here is what I have so far...
Provider prov = emf.find(Provider.class, new Long(ID));
This entity has a many to many relationship that I am trying to add to
List<Organization> orgList = new ArrayList<Organization>();
...
orgList = prov.getOrganizationList();
So I now have the list of entities associated with that entity.
I search for some entities to add and I place them in the orgList...
List<Organization> updatedListofOrgss = emf.createNamedQuery("getOrganizationByOrganizationIds").setParameter("organizationIds", AddThese).getResultList();
List<Organization> deleteListOfOrgs = emf.createNamedQuery("getOrganizationByOrganizationIds").setParameter("organizationIds", DeleteThese).getResultList();
orgList.addAll(updatedListofOrgss);
orgList.removeAll(deleteListOfOrgs);
As you can see I also have a list of delete nodes to remove.
I heard somewhere that you don't need to call persist on such an opperation and that JPA will persist automatically. Well, it doesn't seem to work that way. Can you persist this way, or will I have to go throught the link table entity, and add these values that way?
public class Provider implements Serializable {
#Id
#Column(name="RESOURCE_ID")
private long resourceId;
...
#ManyToMany(fetch=FetchType.EAGER)
#JoinTable(name="DIST_LIST_PERMISSION",
joinColumns=#JoinColumn(name="RESOURCE_ID"),
inverseJoinColumns=#JoinColumn(name="ORGANIZATION_ID"))
private List<Organization> organizationList;
...//getters and setters.
}
The link table that links together organizations and providers...
public class DistListPermission implements Serializable {
#Id
#Column(name="DIST_LIST_PERMISSION_ID")
private long distListPermissionId;
#Column(name="ORGANIZATION_ID")
private BigDecimal organizationId;
#Column(name="RESOURCE_ID")
private Long resourceId;
}
The problem is that you are missing a cascade specification on your #ManyToMany annotation. The default cascade type for #ManyToMany is no cascade types, so any changes to the collection are not persisted. You will also need to add an #ElementDependent annotation to ensure that any objects removed from the collection will be deleted from the database. So, you can change your Provider implementation as follows:
#ManyToMany(fetch=FetchType.EAGER, cascade=CascadeType.ALL)
#ElementDependent
#JoinTable(name="DIST_LIST_PERMISSION",
joinColumns=#JoinColumn(name="RESOURCE_ID"),
inverseJoinColumns=#JoinColumn(name="ORGANIZATION_ID"))
private List<Organization> organizationList;
Since your Provider class is managed, you should not need to merge the entity; the changes should take effect automatically when the transaction is committed.

Hibernate Identifier Name is too long for MySQL Index

I have got a problem with inheritance and the index name generation. As example:
Multiple abstract classes, which are inherited from each other.
#Entity
public abstract class LongClassName1 implements Serializable {
...
#Index(name = "externalIdIndex")
String externalId;
...
}
#Entity
public abstract class LongClassName2 extends LongClassName1 { ... }
#Entity
public abstract class LongClassName3 extends LongClassName2 { ... }
#Entity
public abstract class LongClassName4 extends LongClassName3 { ... }
#Entity
public class LongClassName5 { ... }
Now Hibernate generates an Index like LongClassName5LongClassName4LongClassname3LongClassname2externalIdIndex
which leads to an error message like Identifier name 'LongClassName5LongClassName4LongClassname3LongClassname2externalIdIndex' is too long
I've tried multiple hibernate naming strategies and also have overwritten the methods myself, but nothing has worked so far.
I'm using the hibernate version shipped with JBoss 7.1.1.
Auto generated indexes for the primary key are no problem.
Any ideas what i can do next?
Did your try to manually stablish the index name using the #Table and #Index annotations?
#Table(appliesTo="tableName", indexes = { #Index(name="index1", columnNames={"column1", "column2"} ) } )