How to change method names from jpa-repository? - spring

There is application on spring+jpa(repositories)
Entity:
#Entity
#Getter
#Setter
#NoArgsConstructor
public class User{
private int id;
private String name;
private String surname;
private int age;
}
So, my repository looks like this:
#Repository
public interface UserRepository extends CrudRepository<User, Integer>{
public List<User> findUsersByNameAndAge(String name, int age);
public List<User> findUsersByNameAndSurname(String name, String surname);
}
In my real prod code, there too much params, so this method-name is too long and not comfortable.
Is there a way to make from long method names comfortable options, like just find?

Use default Java 8 feature for wrapping :
for example :
interface UserRepository extends JpaRepository<User, Long> {
// don't use that crazy long method! use getByEmail instead
User findFirstByEmailContainsIgnoreCaseAndField1NotNullAndField2NotNullAndField3NotNullAndField4NotNullAndField5NotNullAndField6NotNull(final String email);
default User getByEmail(final String email) {
return findFirstByEmailContainsIgnoreCaseAndField1NotNullAndField2NotNullAndField3NotNullAndField4NotNullAndField5NotNullAndField6NotNull(email);
}
}
You can find complete reference here : https://github.com/daggerok/spring-data-examples/blob/master/shadov/src/main/java/daggerok/ShadovApplication.java
Or else You can specify any name for a method and add an annotation #Query with parameter value which holds desired query to database like this:
#Query(value="select u from User u where u.deleted=false and u.email=:email")
User findOneByEmail(#Param("email")String email);
or, with native sql query:
#Query(value="SELECT * FROM users WHERE deleted=false AND email=?1", nativeQuery=true)
User findOneByEmail(String email);
You can also use names that follow the naming convention for queries since #Query annotation will take precedence over query from method name.

Related

Spring JPA MYSQL Character Encoding Case Sensitivity

I am using a JPA repository and specified the findByEmail(email) method within. When I call this method it works fine, only problem is I want case sensitivity on it. So, "noemail#noemail" would not match "nOeMaIl#NoEmAiL.cOm". This is not happening as the `findByEmail(email)' method is returning this as true.
When I look at the MYSQL database table, I see the character set as "utf8md4" for each of the fields listed as a string in my entity class. through some reading it looks like case sensitivity works with UTF-8 variations such as "utf8md4_0900_as_cs", not sure how to change this if that is the case.
How can I change things to make sure the findByEmail(email) method returns false when case does not match?
#Entity
#Table(name="users", uniqueConstraints={#UniqueConstraint(columnNames="username"})})
#Data
public class user{
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#NotBlank(message = "Can't be blank")
#Size(max = 250, message = "Can't exceed 60 characters")
#Email
private String email;
public user() {}
public user(String email) {
this.email = email;
}
}
#Repository
public interface UserRepository extends JpaRepository<user, Long> {
List<user> findByEmail(String email);
}
#PostMapping("/v1/endpoint")
public ResponseEntity<?> forgotusername(#RequestBody String email){
List<user> users = userRepository.findByEmail(email);
return new ResponseEntity<>(users, HttpStatus.OK);
}
spring.datasource.url=jdbc:mysql://${MYSQL_HOST:AWS?useUnicode=true&characterEncoding=UTF-8
spring.datasource.username=username
spring.datasource.password=password
If you need case sensitive collation for utf8 fields, you should use utf8_bin. You can extend the MySQL dialect to achieve this. Take a look here.

How to fetch only selected attributes of an entity using Spring JPA?

I'm using Spring Boot (1.3.3.RELEASE) and Hibernate JPA in my project. My entity looks like this:
#Data
#NoArgsConstructor
#Entity
#Table(name = "rule")
public class RuleVO {
#Id
#GeneratedValue
private Long id;
#Column(name = "name", length = 128, nullable = false, unique = true)
private String name;
#Column(name = "tag", length = 256)
private String tag;
#OneToMany(mappedBy = "rule", cascade = CascadeType.ALL, orphanRemoval = true)
private List<RuleOutputArticleVO> outputArticles;
#OneToMany(mappedBy = "rule", cascade = CascadeType.ALL, orphanRemoval = true)
private List<RuleInputArticleVO> inputArticles;
}
My repository looks like this:
#Repository
public interface RuleRepository extends JpaRepository<RuleVO, Long> {
}
In some cases I need to fetch only id and name attributes of entity RuleVO. How can I achieve this? I found a notice it should be doable using Criteria API and Projections but how? Many thanks in advance. Vojtech
UPDATE:
As has been pointed out to me, I'm lazy and this can very well be done hence I'm updating my answer after having looked around the web for a proper one.
Here's an example of how to get only the id's and only the names:
#Repository
public interface RuleRepository extends JpaRepository<RuleVO, Long> {
#Query("SELECT r.id FROM RuleVo r where r.name = :name")
List<Long> findIdByName(#Param("name") String name);
#Query("SELECT r.name FROM RuleVo r where r.id = :id")
String findNameById(#Param("id") Long id);
}
Hopefully this update proves helpful
Old Answer:
Only retrieving the specific attributes name/id is not possible as this is not how spring was designed or any SQL database for that matter as you always select a row which is an entity.
What you CAN do is query over the variables in the entity, for instance:
#Repository
public interface RuleRepository extends JpaRepository<RuleVO, Long> {
public RuleVo findOneByName(String name);
public RuleVo findOneByNameOrId(String name, Long id);
public List<RuleVo> findAllByName(String name);
// etc, depending on what you want
}
You can modify these however you want w.r.t. your needs. You can call these methods directly via the autowired repository
See http://docs.spring.io/spring-data/jpa/docs/current/reference/html/ Section 5.3 for more options and examples
interface IdOnly{
String getId();
}
#Repository
public interface RuleRepository extends JpaRepository<RuleVO, Long> {
public List<IdOnly> findAllByName(String name);
}
I notice that this is a very old post, but if someone is still looking for an answer, try this. It worked for me.
You can also define custom constructor to fetch specific columns using JPQL.
Example:
Replace {javaPackagePath} with complete java package path of the class
use as a constructor in JPQL.
public class RuleVO {
public RuleVO(Long id, String name) {
this.id = id;
this.name = name;
}
}
#Repository
public interface RuleRepository extends JpaRepository<RuleVO, Long> {
#Query("SELECT new {javaPackagePath}.RuleVO(r.id, r.name) FROM RuleVo r where r.name = :name")
List<RuleVO> findIdByName(#Param("name") String name);
}
Yes, you can achieve it with projections. You have many ways to apply them:
If you could upgrade to Spring Data Hopper, it provides an easy to use support for projections. See how to use them in the reference documentation.
Otherwise, first of all create a DTO with the attributes you want to load, something like:
package org.example;
public class RuleProjection {
private final Long id;
private final String name;
public RuleProjection(Long id, String name) {
this.id = id;
this.name = name;
}
public Long getId() {
return id;
}
public String getName() {
return name;
}
}
Of course, you could use Lombok annotations also.
Then, you can use in the JPQL queries like this:
select new org.example.RuleProjection(rule.id, rule.name) from RuleVO rule order by rule.name
Another option, if you want to avoid using DTO class names in your queries, is to implement your own query method using QueryDSL. With Spring Data JPA, you have to:
Create a new interface with the new method. Ex:
public interface RuleRepositoryCustom {
public List<RuleProjection> findAllWithProjection();
}
Change your repository to extend the new interface. Ex:
public interface RuleRepository extends JpaRepository<RuleVO, Long>, RuleRepositoryCustom {
...
Create an implementation of the Custom repository using the Spring Data JPA QueryDSL support. You have to previously generate the Q clases of QueryDSL, using its Maven plugin. Ex:
public class RuleRepositoryImpl {
public List<RuleProjection> findAllWithProjection() {
QRuleVO rule = QRuleVO.ruleVO;
JPQLQuery query = getQueryFrom(rule);
query.orderBy(rule.name.asc());
return query.list(ConstructorExpression.create(RuleProjection.class, rule.id, rule.name));
}
}
You can do it by using #Query annotation(HQL).
Please refer to the Spring docs below:
http://docs.spring.io/spring-data/jpa/docs/current/reference/html/#jpa.query-methods.at-query
(search for #Query in spring document)

Select one column using Spring Data JPA

Does anyone have any idea how to get a single column using Spring Data JPA? I created a repository like below in my Spring Boot project, but always get the {"cause":null,"message":"PersistentEntity must not be null!"} error when accessing the Restful URL.
#RepositoryRestResource(collectionResourceRel = "users", path = "users")
public interface UsersRepository extends CrudRepository<Users, Integer> {
#Query("SELECT u.userName FROM Users u")
public List<String> getUserName();
}
Then if I access the Restful URL like ../users/search/getUserName, I get the error:
{"cause":null,"message":"PersistentEntity must not be null!"}
Create a Projection interface
public interface UserNameOnly {
String getUserName();
}
Then in your repository interface return that type instead of the user type
public interface UserRepository<User> extends JpaRepository<User,String> {
List<UsernameOnly> findNamesByUserNameNotNull();
}
The get method in the projection interface must match a get method of the defined type on the JPA repository, in this case User.
The "findBySomePropertyOnTheObjectThatIsNotNull" allows you to get a List of the entities (as opposed to an Iterable) based on some criteria, which for a findAll can simply be if the unique identifier (or any other NonNull field) is not null.
Concept is : In your entity class create a constructor with only required instant variables. And use that constructor in the repository method shown below.
Lets say you have a interface Repository like below
Repository implementation:
public interface UserRepository<User> extends JpaRepository<User,String>
{
#Query(value = "select new com.org.User(usr.userId) from User usr where usr.name(:name)")
List<User> findUserIdAlone(#Param("name") String user);
}
In Controller
#RestController
public class UserController
{
#Autowired
private UserRepository<User> userRepository;
#Res
public ResponseEntity<User> getUser(#PathVariable("usrname") String userName)
{
User resultUser = usrRepository.findUserIdAlone(userName);
return ResponseEntity.ok(resultUser);
}
}
public class User
{
private String userId,userName;
public User(String userId)
{
this.userId=userId;
}
// setter and getters goes here
}
This Works for me.
public interface UserDataRepository extends JpaRepository<UserData, Long> {
#Query(value = "SELECT emp_name FROM user_data", nativeQuery = true)
public List<Object[]> findEmp_name();
}
System.out.println("data"+ userDataRepository.findEmp_name());
The above line gave me this result :
data[abhijeet, abhijeet1, abhijeet2, abhijeet3, abhijeet4, abhijeet5]
If you want to only return a single column you should look at Projections and Excerpts which will allow you to filter specific columns and other things that are usefule.
If you need list all of the users, try select userName from Users, if you need one user use "where" look at spring data JPA http://docs.spring.io/spring-data/jpa/docs/current/reference/html/ , try change CrudRepository to JpaRepository
It is possible to provide custom implementations of methods in a Spring Data JPA repository, which enables complete control on queries and return types. The approach is as follows:
Define an interface with the desired method signatures.
Implement the interface to achieve the desired behavior.
Have the Repository extend both JpaRepository and the custom interface.
Here is a working example that uses JpaRepository, assuming a user_table with two columns, user_id and user_name.
UserEntity class in model package:
#Entity
#Table(name = "user_table")
public class UserEntity {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
#Column(name = "user_id")
private Long userId;
#Column(name = "user_name")
private String userName;
protected UserEntity() {}
public UserEntity(String userName) {
this.userName = userName;
// standard getters and setters
}
Define interface for the custom repository in the repository package:
public interface UserCustomRepository {
List<String> findUserNames();
}
Provide implementation class for the custom interface in the repository package:
public class UserCustomRepositoryImpl implements UserCustomRepository {
// Spring auto configures a DataSource and JdbcTemplate
// based on the application.properties file. We can use
// autowiring to get a reference to it.
JdbcTemplate jdbcTemplate;
#Autowired
public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
// Now our custom implementation can use the JdbcTemplate
// to perform JPQL queries and return basic datatypes.
#Override
public List<String> findUserNames() throws DataAccessException {
String sql = "SELECT user_name FROM user_table";
return jdbcTemplate.queryForList(sql, String.class);
}
}
Finally, we just need to have the UserRepository extend both JpaRepository and the custom interface we just implemented.
public interface UserRepository extends JpaRepository<UserEntity, Long>, UserCustomRepository {}
Simple test class with junit 5 (assuming the database is initially empty):
#SpringBootTest
class UserRepositoryTest {
private static final String JANE = "Jane";
private static final String JOE = "Joe";
#Autowired
UserRepository repo;
#Test
void shouldFindUserNames() {
UserEntity jane = new UserEntity(JANE);
UserEntity joe = new UserEntity(JOE);
repo.saveAndFlush(jane);
repo.saveAndFlush(joe);
List<UserEntity> users = repo.findAll();
assertEquals(2, users.size());
List<String> names = repo.findUserNames();
assertEquals(2, names.size());
assertTrue(names.contains(JANE));
assertTrue(names.contains(JOE));
}
}

Spring MongoRepository query adding _class field to queries

I have a domain class called User. It uses an object of MyUserId as the Id
#Document(collection = "users")
public class User implements Serializable {
#Property
#Id
private MyUserId id;
#Version
private Integer version;
private String firstName;
// Setters, getters
}
The MyUserId class:
public class MyUserId implements Serializable{
#Property
private String userId;
#Property
private String sampleId;
// setters, getters
}
Inside my Mongo, documents are getting stored as {_id:{userId:....., sampleId:....}, <more fields here>}
My userRepository is like this:
public interface UserRepository extends MongoRepository<User, MyUserId> {
#Query("{'_id': {$in: ?0}}")
List<User> findByUserIds(Collection<MyUserId> userIds);
}
When I'm querying my userRepository, The query is being fired as:
{_id: {$in: [ {_class:"com.sampleuser.MyUserId", userId:"....", sampleId:"...."}, {_class:"com.sampleuser.MyUserId", userId:"....", sampleId:"...."}]}}
It's obvious that it's adding the _class field while querying, but not while storing. Can someone throw some light at how to fix this? It's causing all my queries to fail. Thank you!
There actually exists an issue when using #Query whith complex id types. I'd suggest to use a custom repository implementation until DATAMONGO-1078 is resolved.
Within the custom implementation you could use MongoTemplate to execute the query somehow like this
#Override
public List<User> findByUserIds(Collection<MyUserId> userIds) {
return template.find(query(where("id").in(userIds)), User.class);
}

Is there a repostiory implementation for cross store entities (#Entity #NodeEntity(partial = true))

I have an entity which would be stored in both relational(MySql) and graph database(Neo4j).
#Entity
#NodeEntity(partial = true)
public class User {
#NotNull
#Column(name = "UserName", unique = true)
private String userName;
#GraphProperty
String firstName;
}
I know we have JpaRepository and GraphRepository.
public interface UserRepository extends JpaRepository<User, Long> { }
public interface UserGraphRepository extends GraphRepository<User> { }
But is there any repository implementation for handling such a cross store entity? So I could do something like this.
public interface UserRepository extends CrossStoreRepository<User, Long> { }
So when I call save, it should save in both the databases.
I did some searching and found nothing.So started writing one myself.
If no such thing exist, is there a plan to add one in the future?
Is there any reason why you can't use spring-data-neo4j-cross-store as it is part of the spring-data-neo4j distribution?

Resources