I know there's already a similar question answered previously, but my problem is implementing save with update while there are 3 methods in the interface.
I'm currently using the following methods in my project and don't know how to make saveOrUpdate in this.
The following are my classes:
public interface CompanyRepository extends CrudRepository<Company,Long>{
Company findByCompanyName (String companyName);
List<Company> findAll();
Company findById(Long id);
}
The following is part of my Company Class
#Entity
public class Company extends BaseEntity{
#NotNull
#Size(min = 2, max = 16)
private String companyName;
#Length(max = 60)
private String desc;
//TODO max: add LOGO class later for pic saving
#OneToMany
private List<MobileModel> mobileModels;
public Company()
{
super();
mobileModels = new ArrayList<>();
}
//Getters n setters
}
The following is my baseEntity clas
#MappedSuperclass
public abstract class BaseEntity {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
protected final Long id;
#Version
private Long version;
//Getters n setters
}
Thanks in advance.
I read everywhere and tried so many things for 5 hours.
I just want CompanyRepository to implement all 3 methods without me overriding them in some other class but if I have too then explain how because part of my code is dependent on CompanyRepository. I just wish to add save with update, please explain with respect to my code.
CrudRepository has only save but it acts as update as well.
When you do save on entity with empty id it will do a save.
When you do save on entity with existing id it will do an update that means that after you used findById for example and changed something in your object, you can call save on this object and it will actually do an update because after findById you get an object with populated id that exist in your DB.
save in CrudRepository can accept a single entity or Iterable of your entity type.
putting below if check resolve my issue and save method is working as save and update both when i pass id it updates the record in database and when i dont pass id it save new record in database
place is incoming object in my case and new place is new object of place in which i am setting the place id
if(place.getPlaceId()!=0)
newPlace.setPlaceId(place.getPlaceId());
Related
I know this isn't the best way to define a car class, but I got curious and I ended up writing this:
#Entity
#Table(name = "CAR")
public class Car {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String manufacturer;
private String model;
#ElementCollection
#CollectionTable(
name="ACCESSORY",
joinColumns=#JoinColumn(name="OWNER_ID")
)
#Column(name="ACCESSORIES")
private List<String> accessories;
//getters and setters
}
and its repository
#Repository
public interface CarRepository extends JpaRepository<Car, Long> {
}
Now, considering that I want to create a repository method that finds all the cars that meet a given list of accessories, how can I do it? I was thinking about a method like findById() or something.
By the way, feel free if you want to answer in a way that "Accessories" is an entity.
Disclaimer: Yes, I tried the method List<Car> findByAccessoriesIn(List<String> as); but it brings any car that has at least one of the elements inside the list. I want all the cars that have all items inside the list.
“finds all the cars that meet a given list of accessories“
If i understood correctly then -
findByAccessoriesIn(List yourStrList) should work in this case.
A similar thread is here:
Spring CrudRepository findByInventoryIds(List<Long> inventoryIdList) - equivalent to IN clause
For List in jpa we use “in” where “i” is in caps.
I am using Spring boot framework with hibernate. I want to show all data from database only certain conditions. Here is my query
SELECT * FROM `client_master` WHERE CLIENT_GROUP='S'
I want to get data which CLIENT_GROUP data has only S. I have used bellow cod for spring boot..
Model I have used bellow code..
#Entity
#Table(name = "client_master")
public class ClientMasterModel {
#Id
#GeneratedValue(strategy = GenerationType.SEQUENCE)
#Column(name= "ID")
private int ID;
#Column(name= "NAME")
private String name;
//getter or setter
}
My repository is bellow
public interface Staff_Add_Repository extends JpaRepository<ClientMasterModel, Long> {
}
In service, I have used bellow code..
#Autowired
Staff_Add_Repository add_Repository;
public List<ClientMasterModel> findAll(){
return add_Repository.findAll();
}
Above method returns all data. I want to get only specific data .
How to do it? Please help me..
Try
List<ClientMasterModel> findByClientGroup(String clientGroup);
Assuming you have a field named clientGroup in your ClientMasterModel you just need a correctly named method and possibly - if you wish - a default wrapper method in your repository as following:
public interface Staff_Add_Repository
extends JpaRepository<ClientMasterModel, Long> {
List<ClientMasterModel> findByClientGroup(String clientGroup);
default List<ClientMasterModel> findWhereClientGroupIsS() {
return findByClientGroup("S");
}
}
Also the findAllBy is a synonym to findBy. See this question
I use crnk (JSON-API) in java project and I have 3 questions regarding its usage with spring boot and jpa - haven't found exact implementation details in documentation.
For example, I have 2 entities and respective tables:
#Entity
#JsonApiResource(type = "employee")
public class Employee {
#Id
#JsonApiId
private int id;
private String name;
#ManyToOne
#JoinColumn(name = "typeId")
private EmployeeType employeeType; //stored in table as typeId
}
#Entity
#JsonApiResource(type = "type")
public class EmployeeType {
#Id
#JsonApiId
private int id;
private String typeName;
private int salary;
}
How should JsonApiRelation be introduced in order to be able to call "/employee/1" and "/employee/1/type" urls?
For example there is one more entity.
#Entity
#JsonApiResource(type = "project")
public class Project {
#Id
#JsonApiId
private int id;
private String supervisorName;
private String projectName;
}
First, I'd like to have List of Projects for each Employee, where he is a supervisor, joint by name and have it listed as attribute in Json.
Tried implementing it with #OneToMany and #JoinColumn annotations but got StackOverflowException. How could this be implemented. And second, how could this be implemented with Relation? Like "/employee/1/projects" url.
How should I implement custom filtering of results for findAll method? For example, I have a List of all Employees, but I'd like to exclude some of them from the response. Which class/method should be introduced for this behaviour?
#JsonApiRelation annotation should not be necessary. Crnk will detect the #ManyToOne annotation and map it accordingly.
in case of crnk-jpa it is sufficient to specify all relationships in JPA. Matching JSON API relationships. So your approach seems good. What was the StackoverflowException stacktrace? (next to the examples, there are also many example entities in crnk-jpa)
I would make use of a decorator. See http://www.crnk.io/documentation/#_request_filtering. RepositoryDecoratorFactory allows to place a custom repository between the caller and crnk-jpa (or any other kind of repository). There you can do any kind of modification perform (maybe) calling the "real" repository. => Will add an example for this
feel free also make open up tickets in crnk for any documentation/example clarifications.
I am very new to spring JPA. I have following entity class which I want to insert in table:
#Entity
#Table(name = "test")
public class Test {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id")
private int id;
#Column(name = "user")
private String user;
}
I have an empty table named test. I have multiple objects of Test and I want to insert it to the table. For this I have created a repo class:
#Repository("testRepo")
public interface TestRepo extends JpaRepository<Test, String> {
//write insert query
#Modifying
#Query(//What insert query I should write)
void insertData(#Param("id") String id);
}
I have searched but getting only options for update query.
The method .save(Entity entity), inherited from the Parent interface CrudRepository can be used to both update an existing entity or create a new one.
Your repository interface extends from JpaRepository which extends from CrudRepository. save and saveAndFlush methods can be used as default to insert new rows.
save: Inserts new rows. You can give row list as parameter to this method. In your example it should be used like this:
testRepo.save(testEntity);
or
testRepo.save(testEntities);
saveAndFlush: Inserts only a new row and commit the changes immediately.
In your example it should be used like this:
testRepo.saveAndFlush(testEntity);
In your service class do something similar to below.
You don't have to write a separate method to save the entity. save method of the repository can be used to save the entity.
class TestDAO{
#Autowired
TestRepo testRepo;
public void saveTest(Test test) {
testRepo.save(test);
}
("insert into table values (?1)",nativeQuery = true)
Using spring boot 2.7.5 I'm using JPA Repository with this for instance:
#Query("INSERT INTO Planeta p (nome, clima, terreno) VALUES (:nome, :clima, :terreno)")
Integer insertPlaneta(String nome, String clima, String terreno);
Parameters are passed with :name_of_parameter according with parameters method.
I have to manage a Datatransfer between 2 DBs (mssql) with hibernate.
When i load an object from one DB with session.get() it already has a private key. Then i need to persist it to the other DB with anotherSession.replicate(Object o).
My Problem ist, that the given PK is not persisted but replaced by another one.
PS: Both the srcTable and the destTable have PK generation Identity and it needs to stay that way.
If you map an Entity ID with generation "identity", Hibernate will always generate a new ID as soon as you try to persist it. You will have to switch the generation to "assigned" to keep your old ID.
If you have something like it
#Entity
public class Project {
#Id #GeneratedValue long id; // still set automatically
}
You have to remove the #GeneratedValue annotation from id field. Else jpa will generate a value for id before insertion.
#Entity
public class Project {
#Id long id; // must be initialized by the application
:
}
Solution To Your Problem
Create a an entity containing all the mapping definition.
Create a ID field in your new class without the #Generated value annotation.
Clone the old entity to this new one.
Persist this new entity.
Now if you create a subclass extending your entity then the whole
process becomes very easy.
Sample Code For This Solution
Existing Entity
#Entity
#Table(name="EJB_PROJECT")
public class OldEntity implements Serializable {
#Id
#Column(name="PROJECT_ID", primaryKey=true)
#GeneratedValue
Integer id;
}
New Entity
#Entity
#Inheritance(strategy=SINGLE_TABLE)
#Table(name="EJB_PROJECT")
public class NewEntity extends OldEntity {
#Id
#Column(name="PROJECT_ID", primaryKey=true)
Integer id;
// Constructor to clone old entity's id
public NewEnity(OldEntity old) {
this.id = old.id;
}
}
Persisting code
em.persist(new NewEntity(oldEntity));