I am doing a project where I want to use saveEmployee() method from EmployeeDAO class in EmployeeManager class using a bean.
Employee.java
package com.tutorialspoint.test;
public class Employee {
EmployeeManager employeeManager;
private String fname;
private String lname;
private int dob;
private String add;
private int id;
public void setfname(String fname){
this.fname=fname;
}
public String getfname(){
return fname;
}
public void setlname(String lname){
this.lname=lname;
}
public String getlname(){
return lname;
}
public void setdob(int dob){
this.dob=dob;
}
public int getdob(){
return dob;
}
public void setadd(String add){
this.add=add;
}
public String getadd(){
return add;
}
public void setid(int id){
this.id=id;
}
public int getid(){
return id;
}
public void setEmployeeManager(EmployeeManager employeeManager) {
this.employeeManager = employeeManager;
}
}
EmployeeDAO.java
package com.tutorialspoint.test;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import java.io.Serializable;
public class EmployeeDAO implements Serializable{
private static final long serialVersionUID = 1L;
//SimpleDriverDataSource dataSource = new SimpleDriverDataSource();
private JdbcTemplate jdbcTemplate;
public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
public int saveEmployee(Employee e){
String fname = e.getfname();
String lname = e.getlname();
int dob=e.getdob();
String add=e.getadd();
int id = e.getid();
Object p[] = {fname, lname,dob,add,id};
String query="insert into employee values(?,?,?)";
return jdbcTemplate.update(query, p);
}
public int deleteEmployee(int id){
String sql ="delete from employee where id = ?";
return jdbcTemplate.update(sql, new Object[]{new Integer(id)});
}
public List<Employee> getAllEmployee(){
ResultSet rs = null;
PreparedStatement pst = null;
System.out.println("Connection starting.");
Connection con = getConnection();
String stm = "Select * from employee";
List<Employee> records = new ArrayList<Employee>();
try {
pst = con.prepareStatement(stm);
pst.execute();
rs = pst.getResultSet();
while(rs.next()){
Employee employee = new Employee();
employee.setfname(rs.getString(1));
employee.setlname(rs.getString(2));
employee.setdob(rs.getInt(3));
employee.setadd(rs.getString(4));
employee.setid(rs.getInt(5));
records.add(employee);
}
} catch (SQLException e) {
e.printStackTrace();
}
return records;
}
public Connection getConnection(){
Connection con = null;
String url = "jdbc:postgresql://localhost:5432/testdb";
String user = "postgres";
String password = "postgres";
try {
try {
Class.forName("org.postgresql.Driver");
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
con = DriverManager.getConnection(url, user, password);
System.out.println("Connection completed.");
} catch (SQLException ex) {
System.out.println(ex.getMessage());
}
finally{
}
return con;
}
}
EmployeeManager.java
package com.tutorialspoint.test;
import org.springframework.stereotype.Service;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.tutorialspoint.test.EmployeeDAO;
import com.tutorialspoint.test.Employee;
import java.util.List;
import javax.sql.DataSource;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
public class EmployeeManager {
//EmployeeDAO employeeDao=new EmployeeDAO();
ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
**EmployeeDAO employeeDao= (EmployeeDAO) ctx.getBean("edao");
public void save(){
employeeDao.saveEmployee();
}**
List<Employee>list=employeeDao.getAllEmployee();
}
My code is above. I want to call saveEmployee() method in EmployeeDAO class from EmployeeManager. How can I do that?
public class EmployeeManager {
public void save(){
ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
EmployeeDAO employeeDao = (EmployeeDAO) ctx.getBean("edao");
List<Employee>list = employeeDao.getAllEmployee();
employeeDao.saveEmployee();
}
}
Related
I have 1 collection namely profile now since it has lots of properties and since in future I will be needing more properties i decided to add new data in new collection namely profile_details .I will be keeping 1 field in profile_details namely profileId whose value will be same as primary key of collection profile.
I will be saving data of profile in profile collection using profileRepository.save(profile)
In order to save data in profile_details collection I am using aggregation pipeline in order to save data of profile_details collection but $out operator replaces documents instead of inserting new documents.Below is my sample code.Any help will be deeply appreciated
Profile.java
import java.io.Serializable;
import java.time.Instant;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.annotation.Id;
import org.springframework.data.annotation.LastModifiedDate;
import org.springframework.data.annotation.Transient;
import org.springframework.data.mongodb.core.mapping.Document;
import org.springframework.data.mongodb.core.mapping.Field;
import org.springframework.stereotype.Component;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.juv.common.bean.model.RecentHealthMetricData;
import com.juv.common.enums.CurrentLanding;
import com.juv.common.enums.MFAPreference;
import com.juv.common.enums.Status;
import com.juv.common.primary.bean.model.Answer;
import com.juv.common.primary.bean.model.DeviceIntegrations;
import com.juv.common.primary.bean.model.DeviceToken;
#Document(collection = "profile")
#JsonIgnoreProperties(ignoreUnknown = true)
#Component
public class Profile extends ProfileDetails implements Serializable {
/**
*
*/
private static final long serialVersionUID = 6608898578832145751L;
#Id
private String profileId;
#Field("kibo_user_id")
#JsonProperty("kibo_user_id")
private String kiboUserId;
#Field("new_recommendations")
#JsonProperty("new_recommendations")
private List<String> newRecommendations;
#Field("kibo_id")
#JsonProperty("kibo_id")
private String kiboId;
#Field("original_kibo_id")
#JsonProperty("original_kibo_id")
private String originalKiboId;
#Field("email")
#JsonProperty("email")
private String email;
#Field("country")
#JsonProperty("country")
private String country;
#Field("first_name")
#JsonProperty("first_name")
private String firstName;
#Field("last_name")
#JsonProperty("last_name")
private String lastName;
#CreatedDate
#Field("created_date")
#JsonProperty("created_date")
private Date createdDate;
#Field("registration_date")
#JsonProperty("registration_date")
private Date registrationDate;
#LastModifiedDate
#Field("last_modified")
#JsonProperty("last_modified")
private Date lastModified;
#Field("phi_mapping_id")
#JsonProperty("phi_mapping_id")
private String phiMappingId;
#Field("phone_number")
#JsonProperty("phone_number")
private String phoneNumber;
#Field("origin")
#JsonProperty("origin")
private String origin;
#Field("gender")
#JsonProperty("gender")
private String gender;
#Field("status")
#JsonProperty("status")
private Status status;
#Field("current_landing")
#JsonProperty("current_landing")
private CurrentLanding currentLanding;
#Field("mfa_preference")
#JsonProperty("mfa_preference")
private MFAPreference mfaPreference;
#Field("profile_recommendation_info_id")
#JsonProperty("profile_recommendation_info_id")
private String profileRecommendationInfoId;
#Field("oldest_profile_recommendation_info_id")
#JsonProperty("oldest_profile_recommendation_info_id")
private String oldestProfileRecommendationInfoId;
#Field("last_question")
#JsonProperty("last_question")
private String lastQuestion;
#Field("answers")
#JsonProperty("answers")
private Answer[] answers;
#Field("is_account_locked")
#JsonProperty("is_account_locked")
private boolean isAccountLocked;
#Field("device_integrations")
#JsonProperty("device_integrations")
private DeviceIntegrations deviceIntegrations ;
#Field("profile_photo")
#JsonProperty("profile_photo")
private String profilePhoto;
#Field("device_token_list")
#JsonProperty("device_token_list")
private List<DeviceToken> deviceTokenList;
#Field("unit_map")
#JsonProperty("unit_map")
private Map<String,String> unitMap;
#Field("recent_health_metric_values")
#JsonProperty("recent_health_metric_values")
private Map<String,RecentHealthMetricData> recentHealthMetricValues;
#Field("last_recommendation_info_date")
#JsonProperty("last_recommendation_info_date")
private Date lastRecommendationInfoDate;
#Field("terms_conditions")
#JsonProperty("terms_conditions")
private boolean termsConditions;
#Field("health_metric_preferences")
#JsonProperty("health_metric_preferences")
private Map<String, String> healthMetricPreferences;
#Field("device_preferences")
#JsonProperty("device_preferences")
private Map<Integer, String> devicePreferences;
#Field("pinpoint_custom_atributes")
#JsonProperty("pinpoint_custom_atributes")
private Map<String,String> pinpointCustomAttributes;
#Field("opt_juvlab_customer")
#JsonProperty("opt_juvlab_customer")
private boolean optJuvLabsCustomer;
#Field("deleted")
#JsonProperty("deleted")
private boolean deleted;
#Field("deleted_timestamp")
#JsonProperty("deleted_timestamp")
private Instant deletedTimestamp;
#Field("daily_action_count_clevertap")
#JsonProperty("daily_action_count_clevertap")
private int dailyActionCountClevertap;
public String getProfileId() {
return profileId;
}
public void setProfileId(String profileId) {
this.profileId = profileId;
}
public String getKiboUserId() {
return kiboUserId;
}
public void setKiboUserId(String kiboUserId) {
this.kiboUserId = kiboUserId;
}
public String getKiboId() {
return kiboId;
}
public void setKiboId(String kiboId) {
this.kiboId = kiboId;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
if (email != null) {
email = email.toLowerCase();
}
this.email = email;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public Date getCreatedDate() {
return createdDate;
}
public void setCreatedDate(Date createdDate) {
this.createdDate = createdDate;
}
public Date getRegistrationDate() {
return registrationDate;
}
public void setRegistrationDate(Date registrationDate) {
this.registrationDate = registrationDate;
}
public Date getLastModified() {
return lastModified;
}
public void setLastModified(Date lastModified) {
this.lastModified = lastModified;
}
public String getPhiMappingId() {
return phiMappingId;
}
public void setPhiMappingId(String phiMappingId) {
this.phiMappingId = phiMappingId;
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public String getOrigin() {
return origin;
}
public void setOrigin(String origin) {
this.origin = origin;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public Status getStatus() {
return status;
}
public void setStatus(Status status) {
this.status = status;
}
public CurrentLanding getCurrentLanding() {
return currentLanding;
}
public void setCurrentLanding(CurrentLanding currentLanding) {
this.currentLanding = currentLanding;
}
public MFAPreference getMfaPreference() {
return mfaPreference;
}
public void setMfaPreference(MFAPreference otpPreference) {
this.mfaPreference = otpPreference;
}
public String getProfileRecommendationInfoId() {
return profileRecommendationInfoId;
}
public void setProfileRecommendationInfoId(String profileRecommendationInfoId) {
this.profileRecommendationInfoId = profileRecommendationInfoId;
}
public String getLastQuestion() {
return lastQuestion;
}
public void setLastQuestion(String lastQuestion) {
this.lastQuestion = lastQuestion;
}
public Answer[] getAnswers() {
return answers;
}
public void setAnswers(Answer[] answers) {
this.answers = answers;
}
public boolean isAccountLocked() {
return isAccountLocked;
}
public void setAccountLocked(boolean isAccountLocked) {
this.isAccountLocked = isAccountLocked;
}
public enum ORIGIN {
APP,
KIBO,
SHOPIFY
}
public String getProfilePhoto() {
return profilePhoto;
}
public void setProfilePhoto(String profilePhoto) {
this.profilePhoto = profilePhoto;
}
public DeviceIntegrations getDeviceIntegrations() {
return deviceIntegrations;
}
public void setDeviceIntegrations(DeviceIntegrations deviceIntegrations) {
this.deviceIntegrations = deviceIntegrations;
}
public List<DeviceToken> getDeviceTokenList() {
return deviceTokenList;
}
public void setDeviceTokenList(List<DeviceToken> deviceTokenList) {
this.deviceTokenList = deviceTokenList;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public Map<String, String> getUnitMap() {
return unitMap;
}
public void setUnitMap(Map<String, String> unitMap) {
this.unitMap = unitMap;
}
public Date getLastRecommendationInfoDate() {
return lastRecommendationInfoDate;
}
public void setLastRecommendationInfoDate(Date lastRecommendationInfoDate) {
this.lastRecommendationInfoDate = lastRecommendationInfoDate;
}
public boolean isTermsConditions() {
return termsConditions;
}
public void setTermsConditions(boolean termsConditions) {
this.termsConditions = termsConditions;
}
public Map<String, String> getHealthMetricPreferences() {
return healthMetricPreferences;
}
public void setHealthMetricPreferences(Map<String, String> healthMetricPreferences) {
this.healthMetricPreferences = healthMetricPreferences;
}
public Map<String, String> getPinpointCustomAttributes() {
return pinpointCustomAttributes;
}
public void setPinpointCustomAttributes(Map<String, String> pinpointCustomAttributes) {
this.pinpointCustomAttributes = pinpointCustomAttributes;
}
public Map<Integer, String> getDevicePreferences() {
return devicePreferences;
}
public void setDevicePreferences(Map<Integer, String> devicePreferences) {
this.devicePreferences = devicePreferences;
}
public Map<String, RecentHealthMetricData> getRecentHealthMetricValues() {
if(recentHealthMetricValues==null) {
recentHealthMetricValues = new HashMap<>();
}
return recentHealthMetricValues;
}
public void setRecentHealthMetricValues(Map<String, RecentHealthMetricData> recentHealthMetricValues) {
this.recentHealthMetricValues = recentHealthMetricValues;
}
public List<String> getNewRecommendations() {
return newRecommendations;
}
public void setNewRecommendations(List<String> newRecommendations) {
this.newRecommendations = newRecommendations;
}
public boolean isOptJuvLabsCustomer() {
return optJuvLabsCustomer;
}
public void setOptJuvLabsCustomer(boolean optJuvLabsCustomer) {
this.optJuvLabsCustomer = optJuvLabsCustomer;
}
public boolean isDeleted() {
return deleted;
}
public void setDeleted(boolean deleted) {
this.deleted = deleted;
}
public Instant getDeletedTimestamp() {
return deletedTimestamp;
}
public void setDeletedTimestamp(Instant deletedTimestamp) {
this.deletedTimestamp = deletedTimestamp;
}
public String getOriginalKiboId() {
return originalKiboId;
}
public void setOriginalKiboId(String originalKiboId) {
this.originalKiboId = originalKiboId;
}
public String getOldestProfileRecommendationInfoId() {
return oldestProfileRecommendationInfoId;
}
public void setOldestProfileRecommendationInfoId(String oldestProfileRecommendationInfoId) {
this.oldestProfileRecommendationInfoId = oldestProfileRecommendationInfoId;
}
public int getDailyActionCountClevertap() {
return dailyActionCountClevertap;
}
public void setDailyActionCountClevertap(int dailyActionCountClevertap) {
this.dailyActionCountClevertap = dailyActionCountClevertap;
}
}
ProfileDetails.java
import org.springframework.data.mongodb.core.mapping.Document;
import org.springframework.data.mongodb.core.mapping.Field;
import com.fasterxml.jackson.annotation.JsonProperty;
#Document(collection = "profile_details")
public class ProfileDetails {
#Field("profile_id")
private String profileId;
#Field("partner_code")
#JsonProperty("partner_code")
private String partnerCode;
public String getProfileId() {
return profileId;
}
public void setProfileId(String profileId) {
this.profileId = profileId;
}
public String getPartnerCode() {
return partnerCode;
}
public void setPartnerCode(String partnerCode) {
this.partnerCode = partnerCode;
}
}
ProfileFragmentRepositoryImpl.java
package com.juv.common.secondary.repository.impl;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.AddFieldsOperation;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationOptions;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.aggregation.ArrayOperators.ArrayElemAt;
import org.springframework.data.mongodb.core.aggregation.LimitOperation;
import org.springframework.data.mongodb.core.aggregation.LookupOperation;
import org.springframework.data.mongodb.core.aggregation.MatchOperation;
import org.springframework.data.mongodb.core.aggregation.OutOperation;
import org.springframework.data.mongodb.core.aggregation.SetOperation;
import org.springframework.data.mongodb.core.aggregation.SortOperation;
import org.springframework.data.mongodb.core.aggregation.UnsetOperation;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.stereotype.Component;
import com.juv.common.constants.CommonConstants;
import com.juv.common.secondary.dao.Profile;
import com.juv.common.secondary.dao.ProfileDetails;
import com.juv.common.secondary.repository.ProfileFragmentRepository;
import com.juv.common.secondary.repository.ProfileRepository;
import com.mongodb.internal.operation.InsertOperation;
#Component
public class ProfileFragmentRepositoryImpl implements ProfileFragmentRepository {
#Autowired
private MongoTemplate secondaryMongoTemplate;
#Autowired
private ProfileRepository profileRepository;
#Override
public void saveProfileDetails(Profile profile) {
MatchOperation filterOnProfileId = Aggregation.match(Criteria.where("profileId").is(profile.getProfileId()));
SetOperation setProfileId = SetOperation.set("profileId").toValue(profile.getProfileId());
SetOperation setPartnerCode = SetOperation.set("partnerCode").toValue(profile.getPartnerCode());
OutOperation outOperation = new OutOperation("profile_details").uniqueKey("profileId").insertDocuments();
Aggregation aggregation = Aggregation.newAggregation(filterOnProfileId,setProfileId,setPartnerCode,outOperation);
System.out.println("------------------------"+aggregation);
AggregationResults<ProfileDetails> output = secondaryMongoTemplate.aggregate(aggregation, Profile.class, ProfileDetails.class);
System.out.println("------------------------"+output);
}
}
$out operator replaces documents instead of inserting new documents.How can i make them insert data instead of replacing them
I'm using a One-To-One association between my Member and MemberRoles tables. I wanted them to share the same id as PK and FK in the database and did it. But I've got another problem. When I insert a Member, a MemberRole record is being inserted with it and Member record has the correct id in return response but MemberRole id is incorrect. It returns 0 like this:
{
"result": "Bulk user member saving is successfull. Members' informations are:",
"memberList": [
{
"id": 2,
"firstName": "Michael",
"lastName": "Schumacher",
"email": "ilkay.gune2l#kod5.org",
"enabled": false,
"memberLanguageCode": "tr",
"roleOfMember": {
"id": 0,
"email": "ilkay.gune2l#kod5.org",
"role": "ROLE_USER"
}
}
]
}
My Member Entity Class:
package com.ilkaygunel.entities;
import java.time.LocalDateTime;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToOne;
import javax.persistence.PrimaryKeyJoinColumn;
import javax.persistence.Table;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
#Entity
#JsonInclude(Include.NON_NULL)
#NamedQueries({ #NamedQuery(name = "Member.findAll", query = "select m from Member m"),
#NamedQuery(name = "Member.findByFirstName", query = "select m from Member m where m.firstName =:firstName"),
#NamedQuery(name = "Member.findPasswordOfMember", query = "select m.password from Member m where m.id =:id"),
#NamedQuery(name = "Member.findByActivationToken", query = "select m from Member m where m.activationToken =:activationToken"),
#NamedQuery(name = "Member.findByEmail", query = "select m from Member m where m.email =:email") })
#Table(name = "MEMBER")
public class Member {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "MEMBER_ID")
private long id;
#Column(nullable = false)
private String firstName;
#Column(nullable = false)
private String lastName;
#Column(nullable = false, updatable = false)
private String email;
#Column(nullable = false, updatable = false)
private boolean enabled;
#Column(nullable = false)
private String password;
#Column(nullable = false)
private String memberLanguageCode;
#Column(updatable = false)
#JsonIgnore
private String activationToken;
#Column(updatable = false)
#JsonIgnore
private LocalDateTime activationTokenExpDate;
#OneToOne(cascade = CascadeType.ALL, mappedBy = "member", optional = false)
#PrimaryKeyJoinColumn(name = "MEMBER_ID")
private MemberRoles roleOfMember;
#Override
public String toString() {
return String.format("Member [id=%d, firstName='%s', lastName='%s', email='%s']", id, firstName, lastName,
email);
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
if (null != roleOfMember) {
roleOfMember.setId(id);
}
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public boolean isEnabled() {
return enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public MemberRoles getRoleOfMember() {
return roleOfMember;
}
public void setRoleOfMember(MemberRoles roleOfMember) {
this.roleOfMember = roleOfMember;
}
public String getActivationToken() {
return activationToken;
}
public void setActivationToken(String activationToken) {
this.activationToken = activationToken;
}
public LocalDateTime getActivationTokenExpDate() {
return activationTokenExpDate;
}
public void setActivationTokenExpDate(LocalDateTime activationTokenExpDate) {
this.activationTokenExpDate = activationTokenExpDate;
}
public String getMemberLanguageCode() {
return memberLanguageCode;
}
public void setMemberLanguageCode(String memberLanguageCode) {
this.memberLanguageCode = memberLanguageCode;
}
}
And my MemberRoles Entity class:
package com.ilkaygunel.entities;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.MapsId;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import com.fasterxml.jackson.annotation.JsonIgnore;
#Entity
#NamedQueries({
#NamedQuery(name = "MemberRoles.findByEmail", query = "select mr from MemberRoles mr where mr.email = :email") })
#Table(name = "MEMBERROLES")
public class MemberRoles {
#Id
#Column(name = "MEMBERROLES_ID")
private long id;
private String email;
private String role;
#MapsId
#OneToOne(optional = false)
#JoinColumn(name = "MEMBERROLES_ID", unique = true, nullable = false, updatable = false)
#JsonIgnore
private Member member;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
public Member getMember() {
return member;
}
public void setMember(Member member) {
this.member = member;
}
}
When I inserted a Member record, I check it on the database and see that Member and MemberRoles record have the same id. But why does MemberRoles area in response message has got id as 0?
My MemberSaveService class like this:
package com.ilkaygunel.service;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.mail.MessagingException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import com.ilkaygunel.constants.ConstantFields;
import com.ilkaygunel.entities.Member;
import com.ilkaygunel.entities.MemberRoles;
import com.ilkaygunel.exception.CustomException;
import com.ilkaygunel.exception.ErrorCodes;
import com.ilkaygunel.pojo.MemberOperationPojo;
#Service
public class MemberSaveService extends BaseService {
public MemberOperationPojo addUserMember(List<Member> memberList) {
return addBulkMember(memberList, ConstantFields.ROLE_USER.getConstantField());
}
public MemberOperationPojo addAdminMember(List<Member> memberList) {
return addBulkMember(memberList, ConstantFields.ROLE_ADMIN.getConstantField());
}
public MemberOperationPojo addBulkMember(List<Member> memberList, String role) {
Logger LOGGER = loggingUtil.getLoggerForMemberSaving(this.getClass());
LOGGER.log(Level.INFO, resourceBundleMessageManager.getValueOfProperty(role + "_bulkMemberAddingMethod", "en"));
MemberOperationPojo memberOperationPojo = new MemberOperationPojo();
List<Member> savedMemberList = new ArrayList<>();
try {
memberUtil.checkEmailAddressAndLanguageOnMemberList(memberList, LOGGER);
for (Member member : memberList) {
addOneMember(member, role, LOGGER);
savedMemberList.add(member);
}
memberOperationPojo.setResult(
resourceBundleMessageManager.getValueOfProperty(role + "_bulkMemberAddingSuccessfull", "en"));
memberOperationPojo.setMemberList(memberUtil.removeFieldsFromReturningMember(savedMemberList));
LOGGER.log(Level.INFO,
resourceBundleMessageManager.getValueOfProperty(role + "_bulkMemberAddingSuccessfull", "en")
+ memberList);
} catch (CustomException customException) {
LOGGER.log(Level.SEVERE,
resourceBundleMessageManager.getValueOfProperty(role + "_bulkMemberAddingFaled", "en")
+ customException.getErrorCode() + " " + customException.getErrorMessage());
memberOperationPojo.setErrorCode(customException.getErrorCode());
memberOperationPojo.setResult(customException.getErrorMessage());
} catch (Exception e) {
LOGGER.log(Level.SEVERE,
resourceBundleMessageManager.getValueOfProperty(role + "_bulkMemberAddingFaled", "en")
+ e.getMessage());
memberOperationPojo.setErrorCode(ErrorCodes.ERROR_10.getErrorCode());
memberOperationPojo.setResult(e.getMessage());
}
return memberOperationPojo;
}
private void addOneMember(Member member, String role, Logger LOGGER) throws MessagingException {
MemberOperationPojo memberOperationPojo = new MemberOperationPojo();
LOGGER.log(Level.INFO, resourceBundleMessageManager.getValueOfProperty(role + "_memberAddingMethod",
member.getMemberLanguageCode()));
member.setPassword(getHashedPassword(member.getPassword()));
member.setEnabled(false);
addMemberRolesObject(role, member);
addActivationToken(member);
memberFacade.create(member);
// mailUtil.sendActivationMail(member.getEmail(), member.getActivationToken());
memberOperationPojo.setResult(resourceBundleMessageManager.getValueOfProperty(role + "_memberAddingSuccessfull",
member.getMemberLanguageCode()));
LOGGER.log(Level.INFO, resourceBundleMessageManager.getValueOfProperty(role + "_memberAddingSuccessfull",
member.getMemberLanguageCode()) + member);
}
private String getHashedPassword(String rawPassword) {
return new BCryptPasswordEncoder().encode(rawPassword);
}
private void addMemberRolesObject(String role, Member member) {
MemberRoles rolesOfMember = new MemberRoles();
rolesOfMember.setRole(role);
rolesOfMember.setEmail(member.getEmail());
rolesOfMember.setMember(member);
member.setRoleOfMember(rolesOfMember);
}
private void addActivationToken(Member member) {
String activationToken = UUID.randomUUID().toString();
member.setActivationToken(activationToken);
LocalDateTime activationTokenExpDate = LocalDateTime.now().plusDays(1);
// LocalDateTime activationTokenExpDate = LocalDateTime.now();//Use for expire
// date test!
member.setActivationTokenExpDate(activationTokenExpDate);
}
}
My Web Service End Point Class like this:
package com.ilkaygunel.restservice;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.ilkaygunel.entities.Member;
import com.ilkaygunel.pojo.MemberOperationPojo;
import com.ilkaygunel.service.MemberSaveService;
#RestController
#RequestMapping("/memberPostWebServiceEndPoint")
public class MemberSaveWebServiceEndPoint {
#Autowired
private MemberSaveService memberSaveService;
#RequestMapping(value = "/saveUserMember", method = RequestMethod.POST)
public ResponseEntity<MemberOperationPojo> saveUserMember(#RequestBody List<Member> memberList) {
MemberOperationPojo memberOperationPojo = memberSaveService.addUserMember(memberList);
return new ResponseEntity<MemberOperationPojo>(memberOperationPojo, HttpStatus.OK);
}
#RequestMapping(value = "/saveAdminMember", method = RequestMethod.POST)
public ResponseEntity<MemberOperationPojo> saveAdminMember(#RequestBody List<Member> memberList) {
MemberOperationPojo memberOperationPojo = memberSaveService.addAdminMember(memberList);
return new ResponseEntity<MemberOperationPojo>(memberOperationPojo, HttpStatus.OK);
}
}
Spring Boot Version: 1.5.7.RELEASE
Spring Data
MongoDB
My attempt is to add a simple TODO in TODO Document in MongoDB. I was able to add it if I go by String id.But I want my id to be Long. And my requirement is to generate my own sequence. I am having issues generating sequence with the following code. Appreciate if you point where I am going wrong. I was able to add if I create my own id instead of using a sequence.
package com.srisris.tapasya.springjersey;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.support.SpringBootServletInitializer;
import com.srisris.tapasya.springjersey.domain.ToDo;
import com.srisris.tapasya.springjersey.domain.ToDoSequence;
import com.srisris.tapasya.springjersey.repository.ToDoRepository;
import com.srisris.tapasya.springjersey.repository.ToDoSequenceRepository;
#SpringBootApplication(scanBasePackages = { "com.srisris.tapasya.springjersey" })
public class SpringJerseyApplication extends SpringBootServletInitializer implements CommandLineRunner {
#Autowired
private ToDoRepository todoRepository;
/**
* The repository for the sequence {#link ToDoSequence}
*/
#Autowired
private ToDoSequenceRepository sequenceRepo;
// The sequence key name for the books
private static final String ToDo_SEQ_KEY = ToDo.COLLECTION_NAME;
#Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
return builder.sources(SpringJerseyApplication.class);
}
public static void main(String[] args) {
SpringApplication.run(SpringJerseyApplication.class, args);
}
#Override
public void run(String... arg0) throws Exception {
todoRepository.deleteAll();
bootStrapToDo();
}
private void bootStrapToDo() throws Exception{
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = new Date();
Long sequenceId = sequenceRepo.getNextSequenceId(ToDo_SEQ_KEY);
System.out.println(" Sequence ID is " + sequenceId);
ToDo td1 = new ToDo(sequenceId,"Work on Java", "Learn Lambdas, Modules & clojures", dateFormat.format(date));
todoRepository.save(td1);
//ToDo td2 = new ToDo(sequenceRepo.getNextSequenceId(ToDo_SEQ_KEY),"Work on Swift", "Learn Optionals", dateFormat.format(date));
//todoRepository.save(td2);
}
}
ToDo Domain
package com.srisris.tapasya.springjersey.domain;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
#Document(collection = ToDo.COLLECTION_NAME)
public class ToDo {
public static final String COLLECTION_NAME = "todos";
#Id
private Long id;
private String summary;
private String description;
private String dateCreated;
public ToDo() {
}
public ToDo(Long todoID, String summary, String description, String dateCreated) {
this.id = todoID;
this.summary = summary;
this.description = description;
this.dateCreated = dateCreated;
}
public Long getId() {
return id;
}
public void setId(Long todoID) {
this.id = todoID;
}
public String getSummary() {
return summary;
}
public String getDescription() {
return description;
}
public String getDateCreated() {
return dateCreated;
}
#Override
public String toString() {
return String.format("ToDo[id=%s, summary='%s', description='%s' , dateCreated='%s']", id, summary, description,
dateCreated);
}
}
Custom Sequence Domain
ToDoSequence
package com.srisris.tapasya.springjersey.domain;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
#Document(collection = ToDoSequence.COLLECTION_NAME)
public class ToDoSequence {
public static final String COLLECTION_NAME = "todoSequence";
#Id
private String id;
private Long sequence;
public ToDoSequence() {
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public Long getSequence() {
return sequence;
}
public void setSequence(Long seq) {
this.sequence = seq;
}
}
ToDoRepository
package com.srisris.tapasya.springjersey.repository;
import java.util.List;
import org.springframework.data.mongodb.repository.MongoRepository;
import com.srisris.tapasya.springjersey.domain.ToDo;
public interface ToDoRepository extends MongoRepository<ToDo, Long> {
public ToDo findBySummary(String summary);
public List<ToDo> findByDateCreated(String dateCreated);
}
ToDoSequenceRepository
package com.srisris.tapasya.springjersey.repository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.FindAndModifyOptions;
import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Repository;
import com.srisris.tapasya.springjersey.domain.ToDoSequence;
#Repository
public class ToDoSequenceRepository {
#Autowired
private MongoOperations mongoOperation;
public Long getNextSequenceId(String key) throws Exception {
Query query = new Query(Criteria.where("_id").is(key));
// increase sequence id by 1
Update update = new Update();
update.inc("sequence", 1);
// return new increased id
FindAndModifyOptions options = new FindAndModifyOptions();
options.returnNew(true);
// this is the magic happened.
ToDoSequence seqId = mongoOperation.findAndModify(query, update, options, ToDoSequence.class);
// if no id, throws SequenceException
// optional, just a way to tell user when the sequence id is failed to
// generate.
if (seqId == null) {
throw new Exception(seqId + " Unable to get sequence id for key : " + key);
}
return seqId.getSequence();
}
}
I developed an messaging EJB application with its services that uses WILDFLY 9 server.
Now the application is working and the database is fully functional, I am trying to develop a REST web-service for this app. So I created my RestActivator :
package tn.carmate.webservice;
import javax.ws.rs.ApplicationPath;
import javax.ws.rs.core.Application;
#ApplicationPath("rest")
public class RestActivator extends Application {
}
and my messageRessources.java as follows
package tn.carmate.webservice;
import java.util.List;
import javax.ejb.EJB;
import javax.enterprise.context.RequestScoped;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import tn.esprit.pi.Services.Services;
import tn.esprit.pi.persistance.Message;
#Path("message")
#RequestScoped
public class MessageRessource {
#EJB
Services servicemessage;
#GET
#Produces(MediaType.APPLICATION_JSON)
#Path("{idreceiver}")
public Response getMessageList(#QueryParam(value = "idreceiver") int idReceiver) {
List<Message> message = servicemessage.getMessageList(idReceiver);
return Response.status(Status.OK).entity(message).build();
}
#POST
#Consumes(MediaType.APPLICATION_JSON)
#Path("{idSrc/idDest/content}")
public Response sendMessage(#QueryParam(value = "idSrc") int idSrc, #QueryParam(value = "idDest") int idDest,
#QueryParam(value = "content") String content) {
servicemessage.sendMessage(idSrc, idDest, content);
return Response.status(Status.OK).build();
}
#DELETE
#Path("{idm}")
public Response deleteMessage(#QueryParam(value = "idm") int id) {
servicemessage.deleteMessage(id);
return Response.status(Status.OK).build();
}
#GET
#Produces(MediaType.APPLICATION_JSON)
#Path("{idSender/idReceiver}")
public Response getConversation(#QueryParam(value = "idSender") int idSender,
#QueryParam(value = "idReceiver") int idReceiver) {
List<Message> conversion = servicemessage.getConversation(idSender, idReceiver);
return Response.status(Status.OK).entity(conversion).build();
}
#GET
#Produces(MediaType.APPLICATION_JSON)
#Path("{idR}")
public Response returnInbox (#QueryParam(value = "idR")int idR){
List<Message> listmessage = servicemessage.returnInbox(idR);
return Response.status(Status.OK).entity(listmessage).build();
}
#DELETE
#Path("{idc}")
public Response deleteConversation(#QueryParam(value = "idc")int id){
servicemessage.deleteConversation(id);
return Response.status(Status.OK).build();
}
}
but whenever I try to consume a service like this one I get this error:
This is the message Entity
package tn.esprit.pi.persistance;
import java.io.Serializable;
import java.lang.String;
import java.util.Date;
import javax.persistence.*;
/**
* Entity implementation class for Entity: Message
*
*/
#Entity(name="message")
public class Message implements Serializable {
/* #EmbeddedId
private MessageId Id;
*/
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private int id;
private String object;
private String content;
#Temporal(TemporalType.TIMESTAMP)
private Date dateEmission;
#ManyToOne
private User sender;
#ManyToOne
private User receiver;
private static final long serialVersionUID = 1L;
public Message(User src, User dest, String content) {
this.sender = src;
this.receiver = dest;
this.content = content;
this.dateEmission = new Date();
}
public Message() {
super();
}
/* public MessageId getId() {
return Id;
}public void setId(MessageId id) {
Id = id;
}
*/
public int getIdMessage() {
return this.id;
}
public String getObject() {
return this.object;
}
public void setObject(String object) {
this.object = object;
}
public User getReceiver() {
return this.receiver;
}
public void setReceiver(User reciver) {
this.receiver = reciver;
}
public User getSender() {
return this.sender;
}
public void setSender(User sender) {
this.sender = sender;
}
public String getContent() {
return this.content;
}
public void setContent(String content) {
this.content = content;
}
public Date getDateEmission() {
return this.dateEmission;
}
public void setDateEmission(Date dateEmission) {
this.dateEmission = dateEmission;
}
}
Double check your URL, I think it should be
http://localhost:8080 not http://localhost:18080. Just a typo mistake.
Secondly, Application base path for restful services set to rest
so url should be
http://localhost:8080/CarMate-web/rest/message?idreceiver=1
Finally, idreceiver is a Query Parameter but #Path("{idreceiver}") treat it as path parameter.
So, In http://localhost:8080/CarMate-web/rest/message?idreceiver=1
Rest Endpoint expect a path variable after /message/{idreceiver}?idreceiver=1 as mentioned by #Leonardo in comments.
I would suggest any of below listed solutions:
Remove #Path from method
#GET
#Produces(MediaType.APPLICATION_JSON)
public Response getMessageList(#QueryParam(value = "idreceiver") int idReceiver) {
List<Message> message = servicemessage.getMessageList(idReceiver);
return Response.status(Status.OK).entity(message).build();
}
and use this URL: http://localhost:8080/CarMate-web/rest/message?idreceiver=1
Or Change #Path("{idreceiver}") to #Path("idreceiver")
#GET
#Produces(MediaType.APPLICATION_JSON)
#Path("idreceiver")
public Response getMessageList(#QueryParam(value = "idreceiver") int idReceiver) {
List<Message> message = servicemessage.getMessageList(idReceiver);
return Response.status(Status.OK).entity(message).build();
}
and use this URL: http://localhost:8080/CarMate-web/rest/message/idreceiver?idreceiver=1
I have created a spring boot project, and firstful i have created two entities with their Repository and metier interfaces and a restController and every thing was going well
location class:
package com.agence.entitises;
import java.io.Serializable;
import java.util.Date;
import java.util.List;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
#Entity
public class Location implements Serializable{
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
private Long NumLocation;
private Date DateCreation;
private String Categorie;
private String type;
#ManyToOne
#JoinColumn(name="NUM_LOCAT")
private Locataire locataire;
#ManyToOne
#JoinColumn(name="NUM_CONTRATS")
private Contrats contrats;
#ManyToOne
#JoinColumn(name="NUM_PERIODELOCATION")
private PerieodeLocation periodeLocation;
public Location(Long numLocation, Date dateCreation, String categorie,
String type, Locataire locataire, Contrats contrats,
PerieodeLocation periodeLocation) {
super();
NumLocation = numLocation;
DateCreation = dateCreation;
Categorie = categorie;
this.type = type;
this.locataire = locataire;
this.contrats = contrats;
this.periodeLocation = periodeLocation;
}
public PerieodeLocation getPeriodeLocation() {
return periodeLocation;
}
public void setPeriodeLocation(PerieodeLocation periodeLocation) {
this.periodeLocation = periodeLocation;
}
public Locataire getLocataire() {
return locataire;
}
public void setLocataire(Locataire locataire) {
this.locataire = locataire;
}
public Location(Long numLocation, Date dateCreation, String categorie,
String type) {
super();
NumLocation = numLocation;
DateCreation = dateCreation;
Categorie = categorie;
this.type = type;
}
public Location() {
super();
// TODO Auto-generated constructor stub
}
public Long getNumLocation() {
return NumLocation;
}
public void setNumLocation(Long numLocation) {
NumLocation = numLocation;
}
public Date getDateCreation() {
return DateCreation;
}
public void setDateCreation(Date dateCreation) {
DateCreation = dateCreation;
}
public String getCategorie() {
return Categorie;
}
public void setCategorie(String categorie) {
Categorie = categorie;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public Contrats getContrats() {
return contrats;
}
public void setContrats(Contrats contrats) {
this.contrats = contrats;
}
}
Locataire class:
package com.agence.entitises;
import java.io.Serializable;
import java.sql.Date;
import java.util.List;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
#Entity
public class Locataire implements Serializable {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
private Long NumLocataire ;
private Date dateCreation ;
private String raisonSociale ;
private String nomLocataire ;
private String prenomLocataire ;
private String ville ;
#OneToMany(mappedBy="locataire")
private List<Location> locations;
public Locataire(Long numLocataire, Date dateCreation,
String raisonSociale, String nomLocataire, String prenomLocataire,
String ville, List<Location> locations) {
super();
NumLocataire = numLocataire;
this.dateCreation = dateCreation;
this.raisonSociale = raisonSociale;
this.nomLocataire = nomLocataire;
this.prenomLocataire = prenomLocataire;
this.ville = ville;
this.locations = locations;
}
public String getPrenomLocataire() {
return prenomLocataire;
}
public void setPrenomLocataire(String prenomLocataire) {
this.prenomLocataire = prenomLocataire;
}
public String getVille() {
return ville;
}
public void setVille(String ville) {
this.ville = ville;
}
public List<Location> getLocations() {
return locations;
}
public void setLocations(List<Location> locations) {
this.locations = locations;
}
public Locataire(Long numLocataire, Date dateCreation,
String raisonSociale, String nomLocataire) {
super();
NumLocataire = numLocataire;
this.dateCreation = dateCreation;
this.raisonSociale = raisonSociale;
this.nomLocataire = nomLocataire;
}
public Locataire() {
super();
// TODO Auto-generated constructor stub
}
public Long getNumLocataire() {
return NumLocataire;
}
public void setNumLocataire(Long numLocataire) {
NumLocataire = numLocataire;
}
public Date getDateCreation() {
return dateCreation;
}
public void setDateCreation(Date dateCreation) {
this.dateCreation = dateCreation;
}
public String getRaisonSociale() {
return raisonSociale;
}
public void setRaisonSociale(String raisonSociale) {
this.raisonSociale = raisonSociale;
}
public String getNomLocataire() {
return nomLocataire;
}
public void setNomLocataire(String nomLocataire) {
this.nomLocataire = nomLocataire;
}
}
the Repository Interfaces:
package com.agence.Dao;
import org.springframework.data.jpa.repository.JpaRepository;
import com.agence.entitises.Locataire;
public interface ILocataireRepository extends JpaRepository<Locataire, Long>{
}
package com.agence.Dao;
import org.springframework.data.jpa.repository.JpaRepository;
import com.agence.entitises.Location;
public interface ILocationRepository extends JpaRepository<Location, Long> {
}
LocataireMetier
package com.agence.Metier;
import java.util.List;
import com.agence.entitises.Locataire;
public interface LocataireMetier {
public Locataire saveLocataire(Locataire locataire) ;
public List<Locataire > listeLocataires();
}
LocataireMetierImpl:
package com.agence.Metier;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.agence.Dao.ILocataireRepository;
import com.agence.entitises.Locataire;
#Service
public class LocataireMetierImpl implements LocataireMetier{
#Autowired
private ILocataireRepository locataireRepository ;
#Override
public Locataire saveLocataire(Locataire locataire) {
// TODO Auto-generated method stub
return locataireRepository.save(locataire);
}
#Override
public List<Locataire> listeLocataires() {
// TODO Auto-generated method stub
return locataireRepository.findAll();
}
}
LocataireMetier :
package com.agence.Metier;
import java.util.List;
import com.agence.entitises.Location;
public interface LocationMetier {
public Location saveLocation(Location loc);
public List<Location> listeLocation() ;
}
LocationMetierImpl:
package com.agence.Metier;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.agence.Dao.ILocationRepository;
import com.agence.entitises.Location;
#Service
public class LocationMetierImpl implements LocationMetier{
#Autowired
private ILocationRepository clientRepository ;
#Override
public Location saveLocation(Location loc) {
// TODO Auto-generated method stub
return clientRepository.save(loc);
}
#Override
public List<Location> listeLocation() {
// TODO Auto-generated method stub
return clientRepository.findAll();
}
}
The RestController:
package com.agence.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.agence.Metier.LocataireMetier;
import com.agence.Metier.LocationMetier;
import com.agence.entitises.Locataire;
import com.agence.entitises.Location;
#RestController
public class LocationRestService {
#Autowired
private LocationMetier locationMetier ;
private LocataireMetier locataireMetier ;
#RequestMapping(value="/Locations" ,method=RequestMethod.POST)
public Location saveLocation( #RequestBody Location loc) {
return locationMetier.saveLocation(loc);
}
#RequestMapping(value="/Locations" ,method=RequestMethod.GET)
public List<Location> listeLocation() {
return locationMetier.listeLocation();
}
#RequestMapping(value="/Locataires" ,method=RequestMethod.POST)
public Locataire saveLocataire( #RequestBody Locataire locataire) {
return locataireMetier.saveLocataire( locataire);
}
#RequestMapping(value="/Locataires" ,method=RequestMethod.GET)
public List<Locataire> listeLocataires() {
return locataireMetier.listeLocataires();
}
}
at this case everything works, but when i added the following entities:
Contrats:
package com.agence.entitises;
import java.io.Serializable;
import java.util.Date;
import java.util.List;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
#Entity
public class Contrats implements Serializable{
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
private Long NumContrat ;
private String EtatContrat ;
private Date dateCreation ;
private String referencePeriode ;
private String referenceLocataire ;
#OneToMany(mappedBy="Contrats")
private List<Location> locations;
public Contrats(Long numContrat, String etatContrat, Date dateCreation) {
super();
NumContrat = numContrat;
EtatContrat = etatContrat;
this.dateCreation = dateCreation;
}
public List<Location> getLocations() {
return locations;
}
public void setLocations(List<Location> locations) {
this.locations = locations;
}
public Long getNumContrat() {
return NumContrat;
}
public void setNumContrat(Long numContrat) {
NumContrat = numContrat;
}
public String getEtatContrat() {
return EtatContrat;
}
public void setEtatContrat(String etatContrat) {
EtatContrat = etatContrat;
}
public Date getDateCreation() {
return dateCreation;
}
public void setDateCreation(Date dateCreation) {
this.dateCreation = dateCreation;
}
public String getReferencePeriode() {
return referencePeriode;
}
public void setReferencePeriode(String referencePeriode) {
this.referencePeriode = referencePeriode;
}
public String getReferenceLocataire() {
return referenceLocataire;
}
public void setReferenceLocataire(String referenceLocataire) {
this.referenceLocataire = referenceLocataire;
}
public Contrats() {
super();
// TODO Auto-generated constructor stub
}
public Contrats(Long numContrat, String etatContrat, Date dateCreation,
String referencePeriode, String referenceLocataire) {
super();
NumContrat = numContrat;
EtatContrat = etatContrat;
this.dateCreation = dateCreation;
this.referencePeriode = referencePeriode;
this.referenceLocataire = referenceLocataire;
}
}
PriodeLocation:
package com.agence.entitises;
import java.io.Serializable;
import java.util.Date;
import java.util.List;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
#Entity
public class PerieodeLocation implements Serializable{
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
private Long numPeriode ;
private Long ReferenceLocation ;
private Date dateDebut ;
private Date dateFin ;
private double nombreSemaines ;
private String EtatPeriode ;
#OneToMany(mappedBy="PeriodeLocation")
private List<Location> locations ;
public PerieodeLocation(Long numPeriode, Long referenceLocation,
Date dateDebut, Date dateFin, double nombreSemaines,
String etatPeriode, List<Location> locations) {
super();
this.numPeriode = numPeriode;
ReferenceLocation = referenceLocation;
this.dateDebut = dateDebut;
this.dateFin = dateFin;
this.nombreSemaines = nombreSemaines;
EtatPeriode = etatPeriode;
this.locations = locations;
}
public List<Location> getLocations() {
return locations;
}
public void setLocations(List<Location> locations) {
this.locations = locations;
}
public PerieodeLocation() {
super();
// TODO Auto-generated constructor stub
}
public Long getNumPeriode() {
return numPeriode;
}
public void setNumPeriode(Long numPeriode) {
this.numPeriode = numPeriode;
}
public Long getReferenceLocation() {
return ReferenceLocation;
}
public void setReferenceLocation(Long referenceLocation) {
ReferenceLocation = referenceLocation;
}
public Date getDateDebut() {
return dateDebut;
}
public void setDateDebut(Date dateDebut) {
this.dateDebut = dateDebut;
}
public Date getDateFin() {
return dateFin;
}
public void setDateFin(Date dateFin) {
this.dateFin = dateFin;
}
public double getNombreSemaines() {
return nombreSemaines;
}
public void setNombreSemaines(double nombreSemaines) {
this.nombreSemaines = nombreSemaines;
}
public String getEtatPeriode() {
return EtatPeriode;
}
public void setEtatPeriode(String etatPeriode) {
EtatPeriode = etatPeriode;
}
}
when i execute the app it returns this exception:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaAutoConfiguration.class]: Invocation of init method failed; nested exception is javax.persistence.PersistenceException: [PersistenceUnit: default] Unable to build Hibernate SessionFactory
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1578) ~[spring-beans-4.2.5.RELEASE.jar:4.2.5.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:545) ~[spring-beans-4.2.5.RELEASE.jar:4.2.5.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482) ~[spring-beans-4.2.5.RELEASE.jar:4.2.5.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306) ~[spring-beans-4.2.5.RELEASE.jar:4.2.5.RELEASE]
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) ~[spring-beans-4.2.5.RELEASE.jar:4.2.5.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302) ~[spring-beans-4.2.5.RELEASE.jar:4.2.5.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197) ~[spring-beans-4.2.5.RELEASE.jar:4.2.5.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1054) ~[spring-context-4.2.5.RELEASE.jar:4.2.5.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:829) ~[spring-context-4.2.5.RELEASE.jar:4.2.5.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:538) ~[spring-context-4.2.5.RELEASE.jar:4.2.5.RELEASE]
at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:118) ~[spring-boot-1.3.3.RELEASE.jar:1.3.3.RELEASE]
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:766) [spring-boot-1.3.3.RELEASE.jar:1.3.3.RELEASE]
at org.springframework.boot.SpringApplication.createAndRefreshContext(SpringApplication.java:361) [spring-boot-1.3.3.RELEASE.jar:1.3.3.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:307) [spring-boot-1.3.3.RELEASE.jar:1.3.3.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1191) [spring-boot-1.3.3.RELEASE.jar:1.3.3.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1180) [spring-boot-1.3.3.RELEASE.jar:1.3.3.RELEASE]
at com.agence.AgenceTouristique2Application.main(AgenceTouristique2Application.java:13) [classes/:na]
Caused by: javax.persistence.PersistenceException: [PersistenceUnit: default] Unable to build Hibernate SessionFactory
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.persistenceException(EntityManagerFactoryBuilderImpl.java:1249) ~[hibernate-entitymanager-4.3.11.Final.jar:4.3.11.Final]
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.access$600(EntityManagerFactoryBuilderImpl.java:120) ~[hibernate-entitymanager-4.3.11.Final.jar:4.3.11.Final]
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl$4.perform(EntityManagerFactoryBuilderImpl.java:860) ~[hibernate-entitymanager-4.3.11.Final.jar:4.3.11.Final]
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl$4.perform(EntityManagerFactoryBuilderImpl.java:850) ~[hibernate-entitymanager-4.3.11.Final.jar:4.3.11.Final]
at org.hibernate.boot.registry.classloading.internal.ClassLoaderServiceImpl.withTccl(ClassLoaderServiceImpl.java:425) ~[hibernate-core-4.3.11.Final.jar:4.3.11.Final]
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:849) ~[hibernate-entitymanager-4.3.11.Final.jar:4.3.11.Final]
at org.springframework.orm.jpa.vendor.SpringHibernateJpaPersistenceProvider.createContainerEntityManagerFactory(SpringHibernateJpaPersistenceProvider.java:60) ~[spring-orm-4.2.5.RELEASE.jar:4.2.5.RELEASE]
at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:343) ~[spring-orm-4.2.5.RELEASE.jar:4.2.5.RELEASE]
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:319) ~[spring-orm-4.2.5.RELEASE.jar:4.2.5.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1637) ~[spring-beans-4.2.5.RELEASE.jar:4.2.5.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1574) ~[spring-beans-4.2.5.RELEASE.jar:4.2.5.RELEASE]
... 16 common frames omitted
Caused by: org.hibernate.AnnotationException: mappedBy reference an unknown target entity property: com.agence.entitises.Location.PeriodeLocation in com.agence.entitises.PerieodeLocation.locations
at org.hibernate.cfg.annotations.CollectionBinder.bindStarToManySecondPass(CollectionBinder.java:769) ~[hibernate-core-4.3.11.Final.jar:4.3.11.Final]
at org.hibernate.cfg.annotations.CollectionBinder$1.secondPass(CollectionBinder.java:729) ~[hibernate-core-4.3.11.Final.jar:4.3.11.Final]
at org.hibernate.cfg.CollectionSecondPass.doSecondPass(CollectionSecondPass.java:70) ~[hibernate-core-4.3.11.Final.jar:4.3.11.Final]
at org.hibernate.cfg.Configuration.originalSecondPassCompile(Configuration.java:1697) ~[hibernate-core-4.3.11.Final.jar:4.3.11.Final]
at org.hibernate.cfg.Configuration.secondPassCompile(Configuration.java:1426) ~[hibernate-core-4.3.11.Final.jar:4.3.11.Final]
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1846) ~[hibernate-core-4.3.11.Final.jar:4.3.11.Final]
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl$4.perform(EntityManagerFactoryBuilderImpl.java:857) ~[hibernate-entitymanager-4.3.11.Final.jar:4.3.11.Final]
... 24 common frames omitted
2016-05-10 20:40:18.330 INFO 3148 --- [ main] .b.l.ClasspathLoggingApplicationListener : Application failed to start with classpath: [file:/C:/Users/Lemin/workspace/AgenceTouristique2/target/classes/, file:/C:/Users/Lemin/.m2/repository/org/springframework/boot/spring-boot-starter-data-jpa/1.3.3.RELEASE/spring-boot-starter-data-jpa-1.3.3.RELEASE.jar, file:/C:/Users/Lemin/.m2/repository/org/springframework/boot/spring-boot-starter/1.3.3.RELEASE/spring-boot-starter-1.3.3.RELEASE.jar, file:/C:/Users/Lemin/.m2/repository/org/springframework/boot/spring-boot/1.3.3.RELEASE/spring-boot-1.3.3.RELEASE.jar, file:/C:/Users/Lemin/.m2/repository/org/springframework/boot/spring-boot-autoconfigure/1.3.3.RELEASE/spring-boot-autoconfigure-1.3.3.RELEASE.jar, file:/C:/Users/Lemin/.m2/repository/org/springframework/boot/spring-boot-starter-logging/1.3.3.RELEASE/spring-boot-starter-logging-1.3.3.RELEASE.jar, file:/C:/Users/Lemin/.m2/repository/ch/qos/logback/logback-classic/1.1.5/logback-classic-1.1.5.jar, file:/C:/Users/Lemin/.m2/repository/ch/qos/logback/logback-core/1.1.5/logback-core-1.1.5.jar, file:/C:/Users/Lemin/.m2/repository/org/slf4j/jul-to-slf4j/1.7.16/jul-to-slf4j-1.7.16.jar, file:/C:/Users/Lemin/.m2/repository/org/slf4j/log4j-over-slf4j/1.7.16/log4j-over-slf4j-1.7.16.jar, file:/C:/Users/Lemin/.m2/repository/org/yaml/snakeyaml/1.16/snakeyaml-1.16.jar, file:/C:/Users/Lemin/.m2/repository/org/springframework/boot/spring-boot-starter-aop/1.3.3.RELEASE/spring-boot-starter-aop-1.3.3.RELEASE.jar, file:/C:/Users/Lemin/.m2/repository/org/springframework/spring-aop/4.2.5.RELEASE/spring-aop-4.2.5.RELEASE.jar, file:/C:/Users/Lemin/.m2/repository/aopalliance/aopalliance/1.0/aopalliance-1.0.jar, file:/C:/Users/Lemin/.m2/repository/org/aspectj/aspectjweaver/1.8.8/aspectjweaver-1.8.8.jar, file:/C:/Users/Lemin/.m2/repository/org/springframework/boot/spring-boot-starter-jdbc/1.3.3.RELEASE/spring-boot-starter-jdbc-1.3.3.RELEASE.jar, file:/C:/Users/Lemin/.m2/repository/org/apache/tomcat/tomcat-jdbc/8.0.32/tomcat-jdbc-8.0.32.jar, file:/C:/Users/Lemin/.m2/repository/org/apache/tomcat/tomcat-juli/8.0.32/tomcat-juli-8.0.32.jar, file:/C:/Users/Lemin/.m2/repository/org/springframework/spring-jdbc/4.2.5.RELEASE/spring-jdbc-4.2.5.RELEASE.jar, file:/C:/Users/Lemin/.m2/repository/org/hibernate/hibernate-entitymanager/4.3.11.Final/hibernate-entitymanager-4.3.11.Final.jar, file:/C:/Users/Lemin/.m2/repository/org/jboss/logging/jboss-logging/3.3.0.Final/jboss-logging-3.3.0.Final.jar, file:/C:/Users/Lemin/.m2/repository/org/jboss/logging/jboss-logging-annotations/1.2.0.Beta1/jboss-logging-annotations-1.2.0.Beta1.jar, file:/C:/Users/Lemin/.m2/repository/org/hibernate/hibernate-core/4.3.11.Final/hibernate-core-4.3.11.Final.jar, file:/C:/Users/Lemin/.m2/repository/antlr/antlr/2.7.7/antlr-2.7.7.jar, file:/C:/Users/Lemin/.m2/repository/org/jboss/jandex/1.1.0.Final/jandex-1.1.0.Final.jar, file:/C:/Users/Lemin/.m2/repository/dom4j/dom4j/1.6.1/dom4j-1.6.1.jar, file:/C:/Users/Lemin/.m2/repository/xml-apis/xml-apis/1.0.b2/xml-apis-1.0.b2.jar, file:/C:/Users/Lemin/.m2/repository/org/hibernate/common/hibernate-commons-annotations/4.0.5.Final/hibernate-commons-annotations-4.0.5.Final.jar, file:/C:/Users/Lemin/.m2/repository/org/hibernate/javax/persistence/hibernate-jpa-2.1-api/1.0.0.Final/hibernate-jpa-2.1-api-1.0.0.Final.jar, file:/C:/Users/Lemin/.m2/repository/org/javassist/javassist/3.18.1-GA/javassist-3.18.1-GA.jar, file:/C:/Users/Lemin/.m2/repository/javax/transaction/javax.transaction-api/1.2/javax.transaction-api-1.2.jar, file:/C:/Users/Lemin/.m2/repository/org/springframework/data/spring-data-jpa/1.9.4.RELEASE/spring-data-jpa-1.9.4.RELEASE.jar, file:/C:/Users/Lemin/.m2/repository/org/springframework/data/spring-data-commons/1.11.4.RELEASE/spring-data-commons-1.11.4.RELEASE.jar, file:/C:/Users/Lemin/.m2/repository/org/springframework/spring-orm/4.2.5.RELEASE/spring-orm-4.2.5.RELEASE.jar, file:/C:/Users/Lemin/.m2/repository/org/springframework/spring-context/4.2.5.RELEASE/spring-context-4.2.5.RELEASE.jar, file:/C:/Users/Lemin/.m2/repository/org/springframework/spring-tx/4.2.5.RELEASE/spring-tx-4.2.5.RELEASE.jar, file:/C:/Users/Lemin/.m2/repository/org/springframework/spring-beans/4.2.5.RELEASE/spring-beans-4.2.5.RELEASE.jar, file:/C:/Users/Lemin/.m2/repository/org/slf4j/slf4j-api/1.7.16/slf4j-api-1.7.16.jar, file:/C:/Users/Lemin/.m2/repository/org/slf4j/jcl-over-slf4j/1.7.16/jcl-over-slf4j-1.7.16.jar, file:/C:/Users/Lemin/.m2/repository/org/springframework/spring-aspects/4.2.5.RELEASE/spring-aspects-4.2.5.RELEASE.jar, file:/C:/Users/Lemin/.m2/repository/org/springframework/boot/spring-boot-starter-web/1.3.3.RELEASE/spring-boot-starter-web-1.3.3.RELEASE.jar, file:/C:/Users/Lemin/.m2/repository/org/springframework/boot/spring-boot-starter-tomcat/1.3.3.RELEASE/spring-boot-starter-tomcat-1.3.3.RELEASE.jar, file:/C:/Users/Lemin/.m2/repository/org/apache/tomcat/embed/tomcat-embed-core/8.0.32/tomcat-embed-core-8.0.32.jar, file:/C:/Users/Lemin/.m2/repository/org/apache/tomcat/embed/tomcat-embed-el/8.0.32/tomcat-embed-el-8.0.32.jar, file:/C:/Users/Lemin/.m2/repository/org/apache/tomcat/embed/tomcat-embed-logging-juli/8.0.32/tomcat-embed-logging-juli-8.0.32.jar, file:/C:/Users/Lemin/.m2/repository/org/apache/tomcat/embed/tomcat-embed-websocket/8.0.32/tomcat-embed-websocket-8.0.32.jar, file:/C:/Users/Lemin/.m2/repository/org/springframework/boot/spring-boot-starter-validation/1.3.3.RELEASE/spring-boot-starter-validation-1.3.3.RELEASE.jar, file:/C:/Users/Lemin/.m2/repository/org/hibernate/hibernate-validator/5.2.4.Final/hibernate-validator-5.2.4.Final.jar, file:/C:/Users/Lemin/.m2/repository/javax/validation/validation-api/1.1.0.Final/validation-api-1.1.0.Final.jar, file:/C:/Users/Lemin/.m2/repository/com/fasterxml/classmate/1.1.0/classmate-1.1.0.jar, file:/C:/Users/Lemin/.m2/repository/com/fasterxml/jackson/core/jackson-databind/2.6.5/jackson-databind-2.6.5.jar, file:/C:/Users/Lemin/.m2/repository/com/fasterxml/jackson/core/jackson-annotations/2.6.5/jackson-annotations-2.6.5.jar, file:/C:/Users/Lemin/.m2/repository/com/fasterxml/jackson/core/jackson-core/2.6.5/jackson-core-2.6.5.jar, file:/C:/Users/Lemin/.m2/repository/org/springframework/spring-web/4.2.5.RELEASE/spring-web-4.2.5.RELEASE.jar, file:/C:/Users/Lemin/.m2/repository/org/springframework/spring-webmvc/4.2.5.RELEASE/spring-webmvc-4.2.5.RELEASE.jar, file:/C:/Users/Lemin/.m2/repository/org/springframework/spring-expression/4.2.5.RELEASE/spring-expression-4.2.5.RELEASE.jar, file:/C:/Users/Lemin/.m2/repository/mysql/mysql-connector-java/5.1.38/mysql-connector-java-5.1.38.jar, file:/C:/Users/Lemin/.m2/repository/org/springframework/spring-core/4.2.5.RELEASE/spring-core-4.2.5.RELEASE.jar, file:/C:/Users/Lemin/.m2/repository/org/scala-lang/scala-library/2.11.0/scala-library-2.11.0.jar]
please anyhelp i have to handle this exception