Using #Id on methods - spring-data

I would like to annotate a method with Spring Data #Id but it only works with fields, despite the fact that the annotation can be used on methods.
Is there a way to use #Id on methods too?
I'm using Spring Boot 1.3.0.RELEASE
EDIT
Actually I have this interface that will have an instance being created at runtime.
import org.springframework.data.annotation.Id;
#Document(indexName = "index", type = "document")
public interface Document {
#Id
Integer getId();
}
And this repository.
public interface DocumentRepository extends ElasticsearchCrudRepository<Document, Integer> {
}
Problem is that SimpleElasticsearchPersistentProperty from spring-data-elasticsearch 1.3.0.RELEASE always look for fields:
https://github.com/spring-projects/spring-data-elasticsearch/blob/1.3.0.RELEASE/src/main/java/org/springframework/data/elasticsearch/core/mapping/SimpleElasticsearchPersistentProperty.java
That way if I create an asbtract class instead and put #Id on a field, everything works fine.

The #Id annotation does work on properties, i.e. you can put it on getters, setters or fields. If this does not work something is wrong. Possible reasons are:
the names don't fit the property conventions
you are using the wrong #Id annotation
It does not work on arbitrary methods because Spring Data wouldn't be able to determine a name for that non-property, which in turn is required for many features.

Related

Do self referencing entities need #OneToOne JPA annotations or not?

Imagine an Entity A has a non-mandatory one-to-one relationship with itself, say something like the diagram below.
Do I write sourceTransaction and destinationTransaction as: public DepositAccountTransaction sourceTransaction; public DepositAccountTransaction destinationTransaction; without any annotations?
No you always will need the annotation. If it is optional:
#OneToOne(optional = true)
private DepositAccountTransaction destinationTransaction;
I wouldn't declare any property as public btw. You may want to use projectlombok to generate getters and setters.

Spring Data JPA repository methods don't recognize property names with underscores

I have underscores in the entity property names, and when Spring tries to create the JPA repository implementation, it results in an exception trying to resolve the name of the property.
Entity:
#Entity
public class Student {
#Id
private String s_id;
private String s_name;
...
}
Repository:
#Repository
#Transactional
public interface StudentRepository extends CrudRepository<Student, String> {
List<Student> findByS__name(String name);
}
Exception:
org.springframework.data.mapping.PropertyReferenceException:
No property s found for type Student
It is said here http://docs.spring.io/spring-data/jpa/docs/current/reference/html/
If your property names contain underscores (e.g. first_name) you can
escape the underscore in the method name with a second underscore. For
a first_name property the query method would have to be named
findByFirst__name(…).
I just did as document said, but I still got the exception.
I dont want write #Query by myself, and I need underscore in my property name, how to fix this problem?
I use Spring data jpa 1.8.0.RELEASE + hibernate 4.3.9.Final
Avoid using underscores in the entity property names if you have control over the property naming. This will resolve your repository woes, and will result in a cleaner code-base. Developers dealing with the code after you will thank you.
Note, it's not just my opinion: Spring specifically discourages using underscores.
As we treat underscore as a reserved character we strongly advise to
follow standard Java naming conventions (i.e. not using underscores in
property names but camel case instead).
this JIRA issue shows why the documentation was updated with this reccomendation, and the part describing the double underscore option were removed.
I suspect your root problem is that Spring/Hibernate is not mapping camel case property names to the snake case names you have for your columns in the database. What you really need is for your property name to be interpreted in the SQL that hiberate generates as S_NAME.
Is that why underscores in your property name are "required"? If so, there are a few solutions:
Option 1: #Column annotation
To get JPA/Hibernate to map to the correct column names you can tell it the names explicitly. Use the annotation #Column(name="...") to tell it what column names to use in SQL. Then the field names are not constrained by the column names.
#Entity
public class Student {
#Id
#Column(name="s_id")
private String sId;
#Column(name="s_name")
private String sName;
//...getters and setters...
}
Option 2: Improved Naming Strategy
Or if your application has a large number of entities, rather than adding #Column to every property, change the default naming strategy in your configuration file to the hibernate improved naming strategy.
<prop key="hibernate.ejb.naming_strategy">org.hibernate.cfg.ImprovedNamingStrategy</prop>
This naming strategy will convert camelCase to SNAKE_CASE. Then your class could look as simple as this:
#Entity
public class Student {
#Id
private String sId;
private String sName;
//...getters and setters...
}
Using either of those options, when it creates the SQL it will resolve the column names to:
S_ID
S_NAME
Note: If you are using, or can use Spring Boot, the auto-configuration default will use SpringNamingStrategy, which is a slightly modified version of the hibernate improved strategy. You won't have to do anything to get this improved naming strategy.
The finish line:
Using camel case in your property names you can write your repository method name using camel case, and you can stop trying to wrangle the double underscore:
#Repository
#Transactional
public interface StudentRepository extends CrudRepository<Student, String> {
List<Student> findBySName(String name);
}
Writing double underscore i.e. writing findByS__Name() for property name s_name just does not work. I have tried and tested it. Go by the above answer and change the name of existing instance variables in your entity class. Just dont change getters and setters as they might be used in the existing code.
If you cant change the entities which was my case then better use jqpl query or native sql query on top of repository method
#Query("select s from Student s where s.s_name=?")
List<Student> findBySName();

Why is my projection interface not picked up by Spring Data REST?

I am trying to use up projections with Spring Data REST (version 2.3.0.RELEASE). I read the reference documentation, and gathered that these are the parts I need:
A JPA Entity
#Entity
public class Project implements Serializable {
#Basic(optional = false)
#Column(name = "PROJECT_NAME")
private String projectName;
// ... lots and lots of other stuff
}
A repository that works with that entity
#Repository
public interface ProjectRepository extends JpaRepository<Project, Long> { }
And a projection to retrieve just the name for that entity
#Projection(name="names", types={Project.class})
public interface ProjectProjectionNamesOnly {
String getProjectName();
}
I would like to be able to optionally retrieve just a list of names of projects, and projections seemed perfectly suited to this. So with this setup, I hit my endpoint at http://localhost:9000/projects/1?projection=names. I get back ALL of the attributes and collections links, but I expected to get back just the name and self link.
I also viewed the sample project on projections, but the example is for excerpts, which seems different from projections as it is a different section of the reference. I tried it and it didn't work anyway though.
So the question is this: How do you use spring data rest projections to retrieve just a single attribute of an entity (and its self link)?
Looks like your projection definition is not even discovered and thus it doesn't get applied if you select it for the HTTP request.
For projection interfaces to be auto-discovered they need to be placed inside the very same or a sub-package of the package of the domain type they're bound to.
If you can't put the type into that location, you can manually register a projection definition on RepositoryRestConfiguration by calling ….projectionConfiguration().addProjection(…).
The reference documentation does not really mention this at the moment but there's already a ticket to get this fixed in future versions.

Groovy Mixin persistent properties with JPA

I would like to define a JPA persisted property in a Groovy Mixin and then use it in several entity classes. I couldn't get this to work with JPA annotations and Hibernate - has anyone been successful with this combination?
I have a set up an example Maven project which shows what I'm trying to do and a single JUnit test which defines the behavior I would like.
https://github.com/gilday/groovy-mixin-jpa-test
Briefly:
#Category(Person) class HasPreferences {
#ElementCollection
final Collection<Preference> preferences = []
}
#Entity
#Mixin(HasPreferences)
class Person {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
long id
String name
}
Since #Mixin is dynamic, i doubt JPA will be able to find your mixed properties. I think you need some compile-time code generation, like #Delegate. Even so, JPA will try to persist the generated property. There is a discussion in groovy mailing list concerning the creation of a #Trait annotation which might be what you want.

Form validation in Play 2.0

OK, So I am having some issues with getting data from a form to bind to a model class I have.
I have a class Question that basically looks like this:
#Entity
public class Question extends Model {
#Id #Required public int id;
public String title;
public String body;
...methods...
}
So I want to use this as a template for a form for a user to create a question, so I create a static instance (as they do in the samples)
final static Form<Question> question_form = form(Question.class);
So far so good, everything compiles. The problem comes when I actually submit the form:
Form<Question> filled_form = new Form<Question>(Question.class).bindFromRequest();
Here I get the error:
[UnexpectedTypeException: No validator could be found for type: java.lang.Integer]
My thinking on how to proceed is to use a design pattern that goes like this:
1.) Create template classes specifically for Forms, that don't include things like foreign keys, IDs, and information that isn't in a format designed for the user. (i.e. if the Question has a foreign key for Topic, the QuestionForm class would have a String topic field.
2.) Create a methods in the Question model that goes something like getFormForQuestion(Question) and getQuestionForForm(Form<Question>) and then use these methods to do CRUD functions.
So basically the User and controller interact using Forms, and then the Model knows how to take these forms and turn them into entries in the database.
Is this a reasonable way to proceed? Or is there a better way of doing this?
UPDATE:
Seems to be fixed when using #GeneratedValue annotation rather than the #Required annotation, but I am still curious regarding my proposed Form Design pattern.
Also just removing #Required appears to fix the problems. Still looking for comments on the mentioned design pattern!
id field doesn't need any validation, ORM will care about it. Of course you should not place id in form (it shouldn't be edited at all - it's common AUTO_INCREMENT) And better make it Long, just:
#Id
public Long id;