Hibernate OneToOne bidirectional functionality not working - java

User table not saving PasswordInfo object automatically
Here are my entities
User entity
#Entity
#Table(name = "user")
public class User {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id")
private Long id;
#Column(name = "name")
private String name;
#Column(name = "username")
private String userName;
#Column(name = "password")
private String password;
#Column(name = "emp_id")
private int empId;
#Column(name = "designation")
private String designation;
#Column(name = "status")
private String status;
#Column(name = "email_id")
private String emailId;
#Column(name = "account_status")
private String accountStatus;
#Column(name = "validity_date")
private Date validityDate;
#Column(name = "deactivation_date")
private Date deactivationDate;
#Column(name = "deactivated_by")
private String deactivatedBy;
#Column(name = "deactivation_remarks")
private String deactivationRemarks;
#OneToMany(fetch = FetchType.LAZY,
mappedBy = "user",
cascade = {CascadeType.PERSIST,CascadeType.MERGE,
CascadeType.DETACH,CascadeType.REFRESH})
private List<LoginDetails> loginDetails;
// add convenience methods for bi-directional relationship for LoginDetails
public void add(LoginDetails tempLoginDetails) {
if(loginDetails == null) {
loginDetails = new ArrayList<LoginDetails>();
}
loginDetails.add(tempLoginDetails);
tempLoginDetails.setUser(this);
}
#OneToOne(mappedBy = "user", fetch = FetchType.LAZY,
cascade = {CascadeType.DETACH, CascadeType.MERGE, CascadeType.PERSIST,
CascadeType.REFRESH})
private PasswordInfo passwordInfo;
#ManyToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
#JoinTable(name = "users_roles",
joinColumns = #JoinColumn(name = "user_id"),
inverseJoinColumns = #JoinColumn(name = "role_id"))
private Collection<Role> roles;
#ManyToOne(fetch = FetchType.LAZY,cascade= {CascadeType.PERSIST,CascadeType.MERGE,
CascadeType.DETACH,CascadeType.REFRESH})
#JoinColumn(name="department_id")
private Department department;
#ManyToOne(fetch = FetchType.LAZY,cascade= {CascadeType.PERSIST,CascadeType.MERGE,
CascadeType.DETACH,CascadeType.REFRESH})
#JoinColumn(name="branch_id")
private Branch branch;
/*
* TIMESTAMPS START
* */
#Temporal( TemporalType.TIMESTAMP )
#CreationTimestamp
#Column(name = "creation_date")
private Date creationDate;
#UpdateTimestamp
#Temporal(TemporalType.TIMESTAMP)
#Column(name = "updation_date")
private Date updationDate;
#ManyToOne(fetch = FetchType.LAZY,cascade={CascadeType.DETACH, CascadeType.MERGE, CascadeType.PERSIST,
CascadeType.REFRESH})
#JoinColumn(name="created_by")
private User createdBy;
#OneToMany(mappedBy="createdBy")
private Set<User> createdBySet = new HashSet<User>();
#ManyToOne(fetch = FetchType.LAZY,cascade={CascadeType.DETACH, CascadeType.MERGE, CascadeType.PERSIST,
CascadeType.REFRESH})
#JoinColumn(name="updated_by")
private User updatedBy;
#OneToMany(mappedBy="updatedBy")
private Set<User> updatedBySet = new HashSet<User>();
#PrePersist
protected void onCreate() {
creationDate = new Date();
}
#PreUpdate
protected void onUpdate() {
updationDate = new Date();
}
/*
* TIMESTAMPS END
* */
public User() {
}
// getter and setters and imports are written in real code, i have omitted them here
}
PasswordInfo entity
#Entity
#Table(name = "password_info")
public class PasswordInfo {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id")
private Long id;
#Column(name = "last_password_1")
private String lastPassword1;
#Column(name = "last_password_2")
private String lastPassword2;
#Column(name = "last_password_3")
private String lastPassword3;
#Column(name = "last_password_4")
private String lastPassword4;
#Column(name = "last_password_5")
private String lastPassword5;
#Column(name = "forced_password_flag")
private String forcedPasswordFlag;
#Column(name = "pass_count")
private int passCount;
#Column(name = "password_date")
private Date passwordDate;
#OneToOne(fetch = FetchType.LAZY,cascade = {CascadeType.DETACH, CascadeType.MERGE, CascadeType.PERSIST,
CascadeType.REFRESH})
#JoinColumn(name="user_id")
private User user;
#Temporal( TemporalType.TIMESTAMP )
#CreationTimestamp
#Column(name = "creation_date")
private Date creationDate;
#PrePersist
protected void onCreate() {
creationDate = new Date();
}
public PasswordInfo() {
}
// getter and setters and imports are written in real code, i have omitted them here
}
This is my save method in service class
#Override
#Transactional
public String save(ReportUser reportUser) {
User user = new User();
// assign user details to the user object
user.setUserName(reportUser.getUserName());
user.setPassword(passwordEncoder.encode(reportUser.getPassword()));
user.setName(reportUser.getName());
user.setEmpId(reportUser.getEmpId());
user.setDesignation(reportUser.getDesignation());
user.setEmailId(reportUser.getEmailId());
user.setStatus(reportUser.getStatus());
user.setEmailId(reportUser.getEmailId());
user.setAccountStatus(reportUser.getAccountStatus());
user.setValidityDate(reportUser.getValidityDate());
String loggedInUser = jwtUtil.getUsername();
logger.info(">>>>> Logged In USER " + loggedInUser);
Department theDepartment = departmentDao.getDepartment(reportUser.getDepartmentId());
Branch theBranch = branchDao.getBranch(reportUser.getBranchId());
User createdByUser = userDao.findByUserName(loggedInUser);
user.setBranch(theBranch);
user.setDepartment(theDepartment);
user.setCreatedBy(createdByUser);
String[] roleArr = reportUser.getFormRole().split(",");
List<Role> roleList = new ArrayList<Role>();
for(String r: roleArr) {
roleList.add(roleDao.findRoleByName(r));
}
Collection<Role> roles = roleList;
user.setRoles(roles);
ParameterMst pmst = otherDao.getParameterValueById(1L);
int passwordExpirationDays = Integer.valueOf(pmst.getValue());
PasswordInfo pInfo = new PasswordInfo();
// Add passwordExpirationDays to current date
Date passwordExpirationDate = DateUtils.asDate(LocalDate.now().plusDays(passwordExpirationDays));
logger.info(">>>>> Password Expiration Date " + passwordExpirationDate);
pInfo.setPasswordDate(passwordExpirationDate);
pInfo.setPassCount(12);
pInfo.setUser(user);
user.setPasswordInfo(pInfo);
// save user in the database
userDao.save(user);
return user.getUserName();
}
This is save in DAO Implementation
#Override
public void save(User user) {
// get current hibernate session
Session currentSession = sessionFactory.getCurrentSession();
currentSession.saveOrUpdate(user);
}
Due to bi-directional relationship set in User, i should be able to update both in one go, rather than doing separately.
Why this isn't working?
Please Help!

Don't use mappedBy and #JoinColumn together as they serve slightly different purposes.
See the uses of both and use either one of them.
Try removing #JoinColumn annotation from PasswordInfo entity.

Try to annotate like this
In class PasswordInfo :
#OneToOne(mappedBy = "passwordInfo")
private User user;
In class User
#OneToOne()
private PasswordInfo passwordInfo;
mappedBy say that User table is the owner of the relationship using its propertie passwordInfo.

Related

Update User Details api returns TransientPropertyValueException:

I'm setting an API endpoint that updates an existing user detail, to do that I try to fetch an existing user from the database by id, when I start the application and test with postman it runs the query on my console but displays TransientPropertyValueException: object references an unsaved transient instance - save the transient instance before flushing and fails to make the intended updates. Here is my code
Member
#Getter
#Setter
#AllArgsConstructor
#NoArgsConstructor
#Entity
#Table(name ="member",
indexes = {
#Index(
columnList = "email_address",
name = "email_address_idx",
unique = true
),
},
uniqueConstraints = {
#UniqueConstraint(
columnNames = {"email_address", "phone_number"},
name = "email_address_phone_number_uq"
)
}
)
public class Member {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#Column(name = "first_name", nullable = false)
private String firstName;
#Column(name = "last_name", nullable = false)
private String lastName;
#ManyToOne(fetch = FetchType.EAGER, optional = false)
#JoinColumn(name = "nationality_id")
private Country nationality;
#ManyToOne(fetch = FetchType.EAGER, optional = false)
#JoinColumn(name = "country_of_residence_id")
private Country countryOfResidence;
#Temporal(TemporalType.DATE)
#Column(name ="date_of_birth")
private Date dateOfBirth = new Date();
#Column(name ="current_job_title")
private String currentJobTitle;
#Column(name = "email_address", nullable = false)
private String emailAddress;
#Column(name = "username")
private String username;
#Column(name ="phone_number")
private String phoneNumber;
#Column(name ="city")
private String city;
#Column(name ="state")
private String state;
#Column(name ="password", nullable = false)
private String password;
#Column(name ="avatar")
private String avatar;
#Column(name ="active", nullable = false)
private Boolean active = true;
#CreationTimestamp
#Temporal(TemporalType.TIMESTAMP)
#Column(name = "created_on", updatable = false, nullable = false)
private Date createdOn;
#UpdateTimestamp
#Temporal(TemporalType.TIMESTAMP)
#Column(name = "updated_on", nullable = false)
private Date updatedOn;
#ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
#JoinTable(
name = "member_roles",
joinColumns = #JoinColumn(
name = "member_id", referencedColumnName = "id"),
inverseJoinColumns = #JoinColumn(
name = "role_id", referencedColumnName = "id")
)
private Set<Role> roles = new HashSet<>();
public void addRole(Role role) {
this.getRoles().add(role);
}
public void clearRoles() {
this.roles = new HashSet<>();
}
}
MemberDto
#Getter
#Setter
#AllArgsConstructor
#NoArgsConstructor
public class UpdateMemberDto {
#NotNull(message = "{member.first_name.notNull}")
private String firstName;
#NotNull(message = "{member.last_name.notNull}")
private String lastName;
private Date dateOfBirth;
private String currentJobTitle;
#NotNull(message = "{member.email_address.notNull}")
private String emailAddress;
private String username;
#NotNull(message = "{member.phone_number.notNull}")
private String phoneNumber;
private String city;
private String state;
private String password;
private String avatar;
private Boolean active;
}
ServiceImpl
#Slf4j
#Service
public class UpdateMemberServiceImpl implements UpdateMemberService {
#Autowired
private ModelMapper modelMapper;
private final UpdateMemberRepository repository;
private final MemberJpaRepository jpaRepository;
public UpdateMemberServiceImpl(UpdateMemberRepository repository, MemberJpaRepository jpaRepository) {
this.repository = repository;
this.jpaRepository = jpaRepository;
}
#Override
#Transactional
public Member update(Long id, UpdateMemberDto body) {
Optional<Member> existingMember = jpaRepository.findById(id);
if (existingMember != null) {
Member member = new Member();
member = modelMapper.map(body, Member.class);
member.setId(id);
member = jpaRepository.save(member);
return member;
}
throw new MemberNotFoundException(id);
}
}

How can I implement this Spring Data JPA query by method name that retrieve a specific object based on two properties?

I am working on a Spring Boot project using Spring Data JPA trying to adopt the "query by method name" style in order to define my queries into repositories.
I am finding some difficulties trying to implement a select query retrieving the list of objects based on two different "where condition". I will try to explain what I have to do.
First of all this is my main entity class named Wallet:
#Entity
#Table(name = "wallet")
#Getter
#Setter
#NoArgsConstructor
#AllArgsConstructor
#JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})
public class Wallet implements Serializable {
private static final long serialVersionUID = 6956974379644960088L;
#Id
#Column(name = "id")
#GeneratedValue(strategy=GenerationType.IDENTITY)
private int id;
#Column(name = "address")
private String address;
#Column(name = "notes")
private String notes;
#ManyToOne
#EqualsAndHashCode.Exclude // Needed by Lombock in "Many To One" relathionship to avoid error
#JoinColumn(name = "fk_user_id", referencedColumnName = "id")
#JsonBackReference(value = "user-wallets")
private User user;
#ManyToOne
#EqualsAndHashCode.Exclude // Needed by Lombock in "Many To One" relathionship to avoid error
#JoinColumn(name = "fk_coin_id", referencedColumnName = "id")
private Coin coin;
#ManyToOne
#JoinColumn(name = "type", referencedColumnName = "id")
private WalletType walletType;
public Wallet(String address, String notes, User user, Coin coin, WalletType walletType) {
super();
this.address = address;
this.notes = notes;
this.user = user;
this.coin = coin;
this.walletType = walletType;
}
}
As you can see a wallet is directly binded to a specific User object and to a specific Coin object.
For completeness this is the code of my User entity class:
#Entity
#Table(name = "portal_user")
#Getter
#Setter
#JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})
public class User implements Serializable {
private static final long serialVersionUID = 5062673109048808267L;
#Id
#Column(name = "id")
#GeneratedValue(strategy=GenerationType.IDENTITY)
private Integer id;
#Column(name = "first_name")
#NotNull(message = "{NotNull.User.firstName.Validation}")
private String firstName;
#Column(name = "middle_name")
private String middleName;
#Column(name = "surname")
#NotNull(message = "{NotNull.User.surname.Validation}")
private String surname;
#Column(name = "sex")
#NotNull(message = "{NotNull.User.sex.Validation}")
private char sex;
#Column(name = "birthdate")
#NotNull(message = "{NotNull.User.birthdate.Validation}")
private Date birthdate;
#Column(name = "tax_code")
#NotNull(message = "{NotNull.User.taxCode.Validation}")
private String taxCode;
#Column(name = "e_mail")
#NotNull(message = "{NotNull.User.email.Validation}")
private String email;
#Column(name = "pswd")
#NotNull(message = "{NotNull.User.pswd.Validation}")
private String pswd;
#Column(name = "contact_number")
#NotNull(message = "{NotNull.User.contactNumber.Validation}")
private String contactNumber;
#Temporal(TemporalType.DATE)
#Column(name = "created_at")
private Date createdAt;
#Column(name = "is_active")
private boolean is_active;
#OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL, mappedBy = "user", orphanRemoval = true)
#JsonManagedReference(value = "address")
private Set<Address> addressesList = new HashSet<>();
#ManyToMany(cascade = { CascadeType.MERGE })
#JoinTable(
name = "portal_user_user_type",
joinColumns = { #JoinColumn(name = "portal_user_id_fk") },
inverseJoinColumns = { #JoinColumn(name = "user_type_id_fk") }
)
private Set<UserType> userTypes;
#ManyToOne(fetch = FetchType.LAZY)
#JsonProperty("subagent")
private User parent;
#OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL, mappedBy = "user", orphanRemoval = true)
#JsonManagedReference(value = "user-wallets")
private Set<Wallet> wallets = new HashSet<>();
public User() {
super();
// TODO Auto-generated constructor stub
}
public User(String firstName, String middleName, String surname, char sex, Date birthdate, String taxCode,
String email, String pswd, String contactNumber, Date createdAt, boolean is_active) {
super();
this.firstName = firstName;
this.middleName = middleName;
this.surname = surname;
this.sex = sex;
this.birthdate = birthdate;
this.taxCode = taxCode;
this.email = email;
this.pswd = pswd;
this.contactNumber = contactNumber;
this.createdAt = createdAt;
this.is_active = is_active;
}
}
and this is the code of my Coin entity class:
#Entity
#Table(name = "coin")
#Getter
#Setter
#NoArgsConstructor
#AllArgsConstructor
#JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})
public class Coin implements Serializable {
private static final long serialVersionUID = 6956974379644960088L;
#Id
#Column(name = "id")
#GeneratedValue(strategy=GenerationType.IDENTITY)
private int id;
#Column(name = "name")
#NotNull(message = "{NotNull.Coin.name.Validation}")
private String name;
#Column(name = "description")
private String description;
#Column(name = "code", unique = true)
#NotNull(message = "{NotNull.Coin.code.Validation}")
private String code;
#Type(type="org.hibernate.type.BinaryType")
#Column(name = "logo")
private byte[] logo;
}
Then I have this WalletRepository interface:
public interface WalletRepository extends JpaRepository<Wallet, Integer> {
}
Here I need to define a query by name method that retrieve a specific wallet of a specific User (I think that I can query by the id field of the User) and based and related to a specific Coin (I think that I can query by the id fied of the Coin).
How can I implement a behavior like this?
The following should work:
public interface WalletRepository extends JpaRepository<Wallet, Integer> {
List<Wallet> findByUserIdAndCoinId();
}
You can read more about this at:
https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#jpa.query-methods.query-creation
https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#repository-query-keywords

How should I get related entity?

I want to understand how to work with related entities in Hibernate.
There are two related entities:
#Entity
#Table(name = "usr")
public class User {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#Column(nullable = false)
private String username;
#Column(nullable = false)
private String password;
#Column(nullable = false)
private String email;
private boolean active;
#Enumerated(EnumType.STRING)
private Role role;
#OneToMany(fetch = FetchType.LAZY,
mappedBy = "responsibleUser", cascade = CascadeType.ALL)
private List<GrowBox> growBoxes;
//def-constructor , getters, setters
}
and
#Entity
#Table(name = "growBoxes")
public class GrowBox {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
Long id;
#Column(nullable = false)
private Integer length;
#Column(nullable = false)
private Integer width;
#Column(nullable = false)
private Integer height;
#OneToMany(fetch = FetchType.LAZY, mappedBy = "responsibleGrowBox", cascade = CascadeType.ALL)
private List<Plant> plants;
#OneToMany(fetch = FetchType.LAZY, mappedBy = "activeGrowBox", cascade = CascadeType.ALL)
private List<Sensor> sensors;
#ManyToOne
#JoinColumn(name = "user_id")
private User responsibleUser;
//def-constructor , getters, setters
}
I have registered mapping using annotations. Hope it is correct. And I want to find box by user Id, but don't know how HQL query should be written. 'Cause there is no "user_id" field in my Box Class. Instead there is "User responsibleUser" field. And smth like this won't work(should not)
#Autowired
SessionFactory sessionFactory;
#Override
public List<GrowBox> findByUser(Long userId) {
Session session = sessionFactory.openSession();
String hqlQuery = "from GrowBox where user_id =: userId";
Query query = session.createQuery(hqlQuery);
List growBoxes = query.getResultList();
session.flush();
session.close();
return growBoxes;
}
A HQL query would be
String hqlQuery = "from GrowBox gb where gb.responsibleUser.id =: userId";

Identifier Generation Exception

I have some problems with identifier generation. I use MySQL database. So, I have two entities:
#Entity
#Table(name = "users", catalog = "test1")
public class User {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name="id", unique=true, nullable=false, updatable=false)
private Long id;
private String username;
private String password;
private boolean enabled;
#JsonBackReference
private Set<UserRole> userRole = new HashSet<UserRole>(0);
#OneToOne(cascade={CascadeType.ALL}, fetch = FetchType.LAZY, targetEntity = Utilisateur.class)
#JoinColumn(name="userUtilisateur")
#JsonManagedReference
private Utilisateur userUtilisateur;
/*.. getters and setters..*/ }
and
#Entity
#Table(name="utilisateur")
public class Utilisateur {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
#Column(name = "firstName")
private String firstName;
#Column(name = "lastName")
private String lastName;
private String fullName;
#Column(name = "age")
private int age;
#OneToMany(mappedBy="utilisateur", targetEntity = Ticket.class, cascade=CascadeType.ALL, fetch=FetchType.EAGER)
#JsonBackReference
private Set<Ticket> tickets = new HashSet<Ticket>(0);
#OneToMany(mappedBy="utilisateur", targetEntity=UserAssignProject.class, cascade=CascadeType.ALL, fetch=FetchType.EAGER)
#JsonBackReference
private Set<UserAssignProject> userAssignProjects = new HashSet<UserAssignProject>(0);
#OneToMany(mappedBy="utilisateur", targetEntity=Message.class, cascade=CascadeType.ALL, fetch=FetchType.EAGER)
#JsonBackReference
private Set<Message> messages = new HashSet<Message>(0);
/*.. getters and setters..*/ }
I have this method in UserDaoImpl:
public void save(User user) {
Utilisateur utilisateur = new Utilisateur();
user.setId(user.getId());
user.setUsername(user.getUsername());
user.setPassword(user.getPassword());
user.setEnabled(true);
user.setUserUtilisateur(utilisateur);
getCurrentSession().save(user);
}
Results:
Exception here
I've tried to use sequence, GenerationType.AUTO..., but it's not working.
Any solutions?
Thanks for your attention!

Many to many org.hibernate.PersistentObjectException: detached entity passed to persist

I write my first java application to read rss stream and use spring, spring-data, hibernate.
My models.
RssFeed:
#Entity(name = "RssFeed")
#Table(name = "FEED")
#JsonIgnoreProperties({"rssChannel"})
public class RssFeed {
#Id
#GeneratedValue
#Column
private Integer id;
#Column(unique = true)
#Index(name = "title_index")
private String title;
#Column
#URL
private String link;
#Column
private String description;
#Column
private String content;
#Column
#Temporal(TemporalType.TIMESTAMP)
private Date pubDate;
#Column
#Temporal(TemporalType.TIMESTAMP)
private Date updateDate;
#ManyToOne
#JoinColumn(name = "channelId")
private RssChannel rssChannel;
#ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
#JoinTable(name = "feed_category",
joinColumns = {#JoinColumn(name = "feed_id", nullable = false, updatable = false)},
inverseJoinColumns = {#JoinColumn(name = "category_id", nullable = false, updatable = false)})
private Set<RssCategory> rssCategories = new LinkedHashSet<RssCategory>();
}
RssChannel:
#Entity(name = "RssChannel")
#Table(name = "Channel",
uniqueConstraints = #UniqueConstraint(columnNames = {"link"}))
#JsonIgnoreProperties({"feeds"})
public class RssChannel implements Serializable{
#Id
#GeneratedValue
#Column
private Integer id;
#Column
private String title;
#Column(unique = true)
#org.hibernate.validator.constraints.URL
private String link;
#Column
#org.hibernate.validator.constraints.URL
private String image;
#Column
private String description;
#OneToMany(mappedBy = "rssChannel", cascade = CascadeType.ALL, orphanRemoval = true)
private List<RssFeed> feeds = new LinkedList<RssFeed>();
}
And RssCategory:
#Entity(name = "RssCategory")
#Table(name = "CATEGORY")
#JsonIgnoreProperties({"rssFeeds"})
public class RssCategory {
#Id
#GeneratedValue
#Column
private Integer id;
#Column(unique = true)
private String title;
#ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER, mappedBy = "rssCategories")
public Set<RssFeed> rssFeeds = new LinkedHashSet<RssFeed>();
}
I use CrudRepository for manipulation with data. When save RssFeed without many to many it`s ok:
RssChannel channel = rssChannelService.get(url.toString());
rssFeed.setRssChannel(channel);
rssFeedService.save(rssFeed);
But when i add RssCategory:
rssCategory rssCategory = rssCategoryService.findOrCreate("test");
rssFeed.getRssCategories().add(rssCategory);
rssFeedService.save(rssFeed);
get exception: rg.hibernate.PersistentObjectException: detached entity passed to persist: RssCategory.
My RssFeedServiceImpl:
#Service
public class RssFeedServiceImpl implements RssFeedService {
#Autowired
private RssChannelDAO rssChannelDAO;
#Autowired
private RssFeedDAO rssFeedDAO;
#Override
public Page<RssFeed> findAll(Pageable pageable) {
return rssFeedDAO.findAll(pageable);
}
#Override
public Page<RssFeed> findAll(int rssChannelId, Pageable pageable) {
RssChannel rssChannel = rssChannelDAO.findOne(rssChannelId);
return rssFeedDAO.findByRssChannel(rssChannel, pageable);
}
#Override
public RssFeed get(String title) {
return rssFeedDAO.findByTitle(title);
}
#Override
public RssFeed save(RssFeed rssFeed) {
return rssFeedDAO.save(rssFeed);
}
}
And RssCategoryServiceImpl:
#Service
public class RssCategoryServiceImpl implements RssCategoryService {
#Autowired
RssCategoryDAO rssCategoryDAO;
#Override
public RssCategory findOrCreate(String title) {
RssCategory category = rssCategoryDAO.findByTitle(title);
if (category == null) {
category = new RssCategory();
category.setTitle(title);
category = rssCategoryDAO.save(category);
}
return category;
}
}
How save many to many?
You probably need to save your RssCategory first, in order to have an ID to store in feed_category table. This last save will be automatically made when you make the assignment:
rssFeed.getRssCategories().add(rssCategory);
but first you need to do:
rssFeedService.save(rssCategory);
Probably you'll need to put this operations within a transaction.

Categories