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"} ) } )
Related
I'm trying to write a "existsBy" query but can't make it work. I know there is a existByID in the JpaRepository, but I need to check by the property student_id. I have tried countless ways of writing the function name, but I can't seem to make it right.
public class Student implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
private long student_id;
+other fields and getters and setters...
#Repository
public interface StudentRepository extends JpaRepository<Student, Long> {
boolean existsByStudentid(Long student_id);
}
Error:
Caused by: org.springframework.data.mapping.PropertyReferenceException: No property student found for type Student!
Spring Data is using the underscore as a reserved character. I think it is not possible to use it this way. I think there is no other option to rename the variable.
https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#repositories.query-methods.query-property-expressions
So the field must be named with the following convention
private long studentId;
(The underscore can be used for traversing nested properties: To resolve this ambiguity you can use _ inside your method name to manually define traversal points.)
The name of your property is student_id
So the query method should be
#Repository
public interface StudentRepository extends JpaRepository<Student, Long> {
boolean existsByStudent_id(Long student_id);
}
Btw: _ in property name is not a recommended style in Java expect for constants
I want to mock an object that has a uuid value but I don't want to install powermock.
Your easiest way to achieve this will be to wrap up your UUID generation.
Suppose you have a class using UUID.randomUUID
public Clazz MyClazz{
public void doSomething(){
UUID uuid = UUID.randomUUID();
}
}
The UUID geneartion is completely tied to the JDK implementation. A solution would to be wrap the UUID generation that could be replaced at test time with a different dependency.
Spring has an interface for this exact senario, https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/util/IdGenerator.html
I'm not suggesting you use Spring for this interface just informational purposes.
You can then wrap up your UUID generation,
public class MyClazz{
private final idGeneartor;
public MyClazz(IdGeneartor idGenerator){
this.idGenerator = idGenerator;
}
public void doSomething(){
UUID uuid =idGenerator.generateId();
}
You can then have multiple implementations of UUID geneartion depending on your needs
public JDKIdGeneartor implements IdGenerator(){
public UUID generateId(){
return UUID.randomUUID();
}
}
And a hardcoded impl that will always return the same UUID.
public HardCodedIdGenerator implements IdGenerator(){
public UUID generateId(){
return UUID.nameUUIDFromBytes("hardcoded".getBytes());
}
}
At test time you can construct your object with the HardCodedIdGeneartor allowing you to know what the generated ID will be and assert more freely.
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
}
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.
I have a Struts2 Action Class configured via annotations. All of the "normal" methods that are annotated with #Action work fine.
However, I need to add a method into the action that returns JSON.
Here is a trimmed down version of my class (dao autowired with Spring):
#Namespace("featureClass")
// define success and input actions for class here
public class FeatureClassAction extends ActionSupport {
FeatureClassDao featureClassDao;
#Autowired
public setFeatureClassDao(FeatureClassDeao featureClassDao) {
this.featureClassDao = featureClassDao;
}
List<FeatureClass> featureClasses;
// snip normal actions
#Action("/featureClassesJSON")
#JSON
public String getFeatureClassesJSON() throws Exception {
featureClasses = featureClassDao.getAll();
return SUCCESS;
}
}
Can anyone assist? If I have to go the struts.xml route, that means moving all of my other actions (which work fine) into it.
I figured I would share the answer, since anyone else with the same problem would likely also face the silence.
I created two actions: FeatureClassAction and FeatureClassJsonAction. FeatureClassAction was annotated as such:
#ParentPackage("struts-default")
#Namespace("/featureClass")
public class FeatureClassAction extends ActionSupport {
FeatureClassJsonAction is annotated like this:
#ParentPackage("json-default")
#Namespace("/featureClass")
public class FeatureClassJsonAction extends ActionSupport {
The method in the JSON Action was annotated like this:
#Action(value="featureClassesJson", results = {
#Result(name="success", type="json")
})
public String getFeatureClassesJSON() throws Exception {
Hope it helps someone.