delete object with a manytomany collection - java

Sitiuation: trying to remove a person that has a collection of persons(friends). Ofcourse i don't want the friends to be delete so i have to be carefull with that.
code for Person:
#Entity
public class Person {
private String naam, voornaam, email, password;
#Id
private String username;
private String status;
#ManyToMany
private Collection<Person> vrienden;
#OneToMany(orphanRemoval = true)
private Collection<Post> posts;
#Enumerated(EnumType.STRING)
private Role role;
public Person(String naam, String voornaam, String email, String password, String username) {
setNaam(naam);
setEmail(email);
setStatus("online");
setVoornaam(voornaam);
setPassword(password);
setUsername(username);
vrienden = new HashSet<>();
posts = new HashSet<>();
role = Role.USER;
}
public static void addFriend(Person a, Person b) {
a.addFriend(b);
b.addFriend(a);
}
private void addFriend(Person b) {
this.vrienden.add(b);
}
public static void deleteFriend(Person a, Person b) {
a.deleteFriend(b);
b.deleteFriend(a);
}
private void deleteFriend(Person a) {
this.vrienden.remove(a);
}
public Collection<Person> getFriends() {
return vrienden;
}
public Role getRole() {
return this.role;
}
public void setRole(Role role) {
this.role = role;
}
#NotNull(message = "{error.no.name}")
#Size(min = 2, message = "{error.invalid.namesize}")
public String getNaam() {
return naam;
}
public void setNaam(String naam) {
this.naam = naam;
}
#NotNull(message = "{error.no.surnaam}")
#Size(min = 2, message = "{error.invalid.surnamesize}")
public String getVoornaam() {
return voornaam;
}
public void setVoornaam(String voornaam) {
this.voornaam = voornaam;
}
#NotNull(message = "{error.no.email}")
#Email(message = "{error.invalid.email}")
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
#NotNull(message = "{error.no.status}")
#Size(min = 1, message = "{error.no.valid.status}")
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
#NotNull(message = "{error.no.username}")
#Size(min = 2, message = "{error.invalid.usernamesize}")
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public void setPassword(String password) {
this.password = Password.getSaltedHash(password);
}
public boolean isPasswordCorrect(String password) {
boolean result = false;
result = Password.check(password, this.password);
return result;
}
#NotNull(message = "{error.no.password}")
#Size(min = 2, message = "{error.invalid.usernamesize}")
public String getPassword() {
return this.password;
}
public void addPost(Post p) {
if (p == null) {
throw new DomainException("Post is null");
}
posts.add(p);
}
public void deletePost(Post p) {
if (p == null) {
throw new DomainException("Post is null");
}
posts.remove(p);
}
public Collection<Post> getPosts() {
return posts;
}
#Override
public int hashCode() {
int hash = 3;
hash = 59 * hash + Objects.hashCode(this.username);
return hash;
}
public void setHashedPassword(String password) {
this.password = password;
}
}
The method that i'm currently using is:
public void DeletePerson(String user) {
entityManager.getTransaction().begin();
entityManager.createQuery("delete from Person p where p.username=:username").setParameter("username", user).executeUpdate();
entityManager.getTransaction().commit();
}
It gives the following error:
java.sql.SQLIntegrityConstraintViolationException: DELETE on table 'PERSON' caused a violation of foreign key constraint 'PRSNPRSNVRNDNSRNME' for key (vincent). The statement has been rolled back.
My guess is to add something to the manytomany annotation
create tables:
https://i.stack.imgur.com/zS2Xf.png
UPDATE:
The code that i use now for deleting succesfully:
public void DeletePerson(String user) {
entityManager.getTransaction().begin();
entityManager.createNativeQuery("delete from PERSON_PERSON p where p.PERSON_USERNAME=?username or p.VRIENDEN_USERNAME=?username").setParameter("username", user).executeUpdate();
entityManager.flush();
Person tempPerson = getPerson(user);
entityManager.remove(tempPerson);
entityManager.getTransaction().commit();
}
but now i still retrieve old references although the data is deleted in the tables. I retrieve that data with:
entityManager.find(Person.class, user);

You cannot delete person that exists as friend in list of another person. First you should remove it from all friend lists (vrienden) in other person objects (rows in db) and than remove it. Error message clearly says that you cannot delete row because that record is FK in other table.

You need to First Delete all Posts and vrienden (Relation - Maybe some intermediate table) then remove current Person (Because Foreign Key Constraint will not allow you to do this - As many other rows from different table may depend on this table.
https://stackoverflow.com/a/1089008/5284920

Related

How to check the user's verification code?

I am very new to Spring Boot. This is what I want to do: The user's email is test#example.com. That user already exists in my database, but I would like to know if their verificationCode is 123.
Entity:
public class Users {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String email;
private String password;
private String verificationCode;
#Column(name = "verified", columnDefinition = "default false")
private boolean verified = false;
#CreationTimestamp
private Date registrationDate;
protected Users() {}
public Users(String email, String password, String verificationCode) {
this.email = email;
this.password = password;
this.verificationCode = verificationCode;
}
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 getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getVerificationCode() {
return verificationCode;
}
public void setVerificationCode(String verificationCode) {
this.verificationCode = verificationCode;
}
public boolean isVerified() {
return verified;
}
public void setVerified(boolean verified) {
this.verified = verified;
}
}
So with userRepository.findByEmail("test#example.com") I am getting the correct user, but how do I check their verification code?
if you're using userRepository.findByEmail("test#example.com"), just take the verification code from entity.
private static final String CODE = "123";
final User user = userRepository.findByEmail("test#example.com");
if (CODE.equals(user.getVerificationCode())) {
// do something
}
Another option to have it within query.
userRepository.findByEmailAndVerificationCode("test#example.com", CODE);
Or you can have something similar as Philipp wrote, but I would not get whole entity just find out if it exist. So solution would be
if (userRepository.existsByCode(CODE)) {
// do something
}
You search for something like that:
public void checkVerificationCode(final String verificationCode) {
final User user = userRepository.findByEmail("test#example.com");
if (!user.getVerificationCode(verificationCode)) {
throw new VerificationCodeException("Incorrect verification code.");
}
}

Spring Mvc- delete user from database

I'm developing small Spring MVC application, and I have a problem with delete customer from mysql database. When I delete customer like a admin, customer disappears only in the customer table and remains in the authority and users tables. The question is how to repair it?
User.class
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int usersId;
private String username;
private String password;
private Boolean enabled;
private int customerId;
public int getUsersId() {
return usersId;
}
public void setUsersId(int usersId) {
this.usersId = usersId;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public Boolean getEnabled() {
return enabled;
}
public void setEnabled(Boolean enabled) {
this.enabled = enabled;
}
public int getCustomerId() {
return customerId;
}
public void setCustomerId(int customerId) {
this.customerId = customerId;
}
}
#Entity
public class Authorities {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int authoritiesId;
private String username;
private String authority;
public int getAuthoritiesId() {
return authoritiesId;
}
public void setAuthoritiesId(int authoritiesId) {
this.authoritiesId = authoritiesId;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getAuthority() {
return authority;
}
public void setAuthority(String authority) {
this.authority = authority;
}
}
#Entity
public class Customer implements Serializable {
private static final long serialVersionUID = 5140900014886997914L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int customerId;
#NotEmpty(message = "Nazwa użytkownika nie może pozostać pusta!")
private String customerName;
#NotEmpty(message = "Uzupełnij adres email!")
private String customerEmail;
private String customerPhone;
#NotEmpty(message = "Nazwa użytkownika nie może pozostać pusta!")
private String username;
#NotEmpty(message = "Uzupełnij hasło!")
#Size(min = 6, max = 16, message = "Hasło musi zawierać od 6 do 16 znaków!")
private String password;
private boolean enabled;
#OneToOne(mappedBy = "customer", cascade = CascadeType.REMOVE)
#JoinColumn(name = "billingAddressId")
private BillingAddress billingAddress;
#OneToOne(mappedBy = "customer", cascade = CascadeType.REMOVE)
#JoinColumn(name = "shippingAddressId")
private ShippingAddress shippingAddress;
#OneToOne( cascade = CascadeType.REMOVE, mappedBy = "customer")
#JoinColumn(name = "cartId")
#JsonIgnore
private Cart cart;
public int getCustomerId() {
return customerId;
}
public void setCustomerId(int customerId) {
this.customerId = customerId;
}
public String getCustomerName() {
return customerName;
}
public void setCustomerName(String customerName) {
this.customerName = customerName;
}
public String getCustomerEmail() {
return customerEmail;
}
public void setCustomerEmail(String customerEmail) {
this.customerEmail = customerEmail;
}
public String getCustomerPhone() {
return customerPhone;
}
public void setCustomerPhone(String customerPhone) {
this.customerPhone = customerPhone;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public boolean isEnabled() {
return enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
public BillingAddress getBillingAddress() {
return billingAddress;
}
public void setBillingAddress(BillingAddress billingAddress) {
this.billingAddress = billingAddress;
}
public ShippingAddress getShippingAddress() {
return shippingAddress;
}
public void setShippingAddress(ShippingAddress shippingAddress) {
this.shippingAddress = shippingAddress;
}
public Cart getCart() {
return cart;
}
public void setCart(Cart cart) {
this.cart = cart;
}
}
#Controller
public class RegisterController {
#RequestMapping("/register")
public String registerCustomer(Model model) {
Customer customer = new Customer();
BillingAddress billingAddress = new BillingAddress();
ShippingAddress shippingAddress = new ShippingAddress();
customer.setBillingAddress(billingAddress);
customer.setShippingAddress(shippingAddress);
model.addAttribute("customer", customer);
return "registerCustomer";
}
#Autowired
private CustomerService customerService;
#RequestMapping(value = "/register", method = RequestMethod.POST)
public String registerCustomerPost(#Valid #ModelAttribute("customer") Customer customer, BindingResult result,
Model model) {
if (result.hasErrors()) {
return "registerCustomer";
}
List<Customer> customerList = customerService.getAllCustomers();
for (int i = 0; i < customerList.size(); i++) {
if (customer.getCustomerEmail().equals(customerList.get(i).getCustomerEmail())) {
model.addAttribute("emailMsg", "Email już istnieje w bazie danych!");
return "registerCustomer";
}
if (customer.getUsername().equals(customerList.get(i).getUsername())) {
model.addAttribute("usernameMsg", "Użytkownik o dane nazwie już istnieje w bazie!");
return "registerCustomer";
}
}
customer.setEnabled(true);
customerService.addCustomer(customer);
return "registerCustomerSuccess";
}
}
#Repository
#Transactional
public class CustomerDaoImpl implements CustomerDao {
#Autowired
private SessionFactory sessionFactory;
public void addCustomer(Customer customer) {
Session session = sessionFactory.getCurrentSession();
customer.getBillingAddress().setCustomer(customer);
customer.getShippingAddress().setCustomer(customer);
session.saveOrUpdate(customer);
session.saveOrUpdate(customer.getBillingAddress());
session.saveOrUpdate(customer.getShippingAddress());
Users newUser = new Users();
newUser.setUsername(customer.getUsername());
newUser.setPassword(customer.getPassword());
newUser.setEnabled(true);
newUser.setCustomerId(customer.getCustomerId());
Authorities newAuthority = new Authorities();
newAuthority.setAuthority("ROLE_USER");
session.saveOrUpdate(newUser);
session.saveOrUpdate(newAuthority);
newAuthority.setUsername(customer.getUsername());
Cart newCart = new Cart();
newCart.setCustomer(customer);
customer.setCart(newCart);
session.saveOrUpdate(customer);
session.saveOrUpdate(newCart);
session.flush();
}
public Customer getCustomerById(int id) {
Session session = sessionFactory.getCurrentSession();
Customer customer = (Customer) session.get(Customer.class, id);
session.flush();
return customer;
}
public List<Customer> getAllCustomers() {
Session session = sessionFactory.getCurrentSession();
Query query = session.createQuery("from Customer ");
List<Customer> customerList = query.list();
return customerList;
}
public Customer getCustomerByUsername(String username) {
Session session = sessionFactory.getCurrentSession();
Query query = session.createQuery("from Customer where username = ?");
query.setString(0, username);
return (Customer) query.uniqueResult();
}
public void deleteCustomer(Customer customer) {
Session session = sessionFactory.getCurrentSession();
session.delete(customer);
session.flush();
}
}
You have to add foreign key constraints between tables and set action as(on delete= cascade).
Your customer entity doesn't have any relationship with user and authority tables, then no delete is performed by jpa.
EDIT
In customer entity instead of username you could have
#OneToOne(mappedBy="username", cascadeType=CascadeType.REMOVE) private User user
The same for Authories entity:
#OneToOne(mappedBy="username", cascadeType=CascadeType.REMOVE) private User user
On your opinion ,the relationship between User and Customer is one to one.And you want to delete User when you delete the Customer .
First we have to explicit the relationship.
In the User Entity , i suggest you to remove the CustomerId , And add User user to Customer Entity.
And the Customer Entity will be :
private User user;
public void setUser(User user){
this.user = user;
}
#OneToOne
public User getUser(){
return this.user;
}
After that ,you can get the User by customer(userId),And when you want to delete the Customer ,you should get the User first,then delete Customer and delete that User

JPA code not executing further after transaction.commit

Main method
EntityManagerFactory emf=Persistence.createEntityManagerFactory("manager1");
EntityManager em1=emf.createEntityManager();
EntityTransaction entityTransaction=em1.getTransaction();
entityTransaction.begin();
Person persons=JPA_basic_Example.setPerson();//fills all the fields of person
Credential cred=JPA_basic_Example.setCredential();//fills all fields of credentials
System.out.println("check1");
cred.setPerson(persons);
persons.setCredential(cred);
em1.persist(cred);
entityTransaction.commit();
em1.close();
emf.close();
Java Bean Credential oneToone Bidirectional with Person
public class Credential {
#Id
#Column(name ="credentialid")
private int credential_id;
private String UserName;
private String Password;
#OneToOne(cascade = CascadeType.ALL)
#JoinColumn(name="Personid")
private Person person;
public String getPassword() {
return Password;
}
public void setPassword(String password) {
Password = password;
}
public int getCredential_id() {
return credential_id;
}
public void setCredential_id(int credential_id) {
this.credential_id = credential_id;
}
public String getUserName() {
return UserName;
}
public void setUserName(String userName) {
UserName = userName;
}
public Person getPerson() {
return person;
}
public void setPerson(Person person) {
this.person = person;
}
}
Java Bean Person
#Entity
public class Person {
#Id
#Column(name ="Personid")
private int person_id;
//#Basic(optional = false)
//#Column(name ="Name", unique = true)
private String name;
#ElementCollection
#CollectionTable
List<String> contact=new ArrayList<String>();
private Address address=new Address();
#OneToOne(mappedBy = "person", orphanRemoval = true )
Credential credential ;
public Credential getCredential() {
return credential;
}
public void setCredential(Credential credential) {
this.credential = credential;
}
public List<String> getContact() {
return contact;
}
public void setContact(List<String> contact) {
this.contact = contact;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getPerson_id() {
return person_id;
}
public void setPerson_id(int person_id) {
this.person_id = person_id;
}
}
Output Console
Hibernate:
insert
into
Person
(area, city, pincode, state, name, Personid)
values
(?, ?, ?, ?, ?, ?)
AFter this code stuck and nit moving forward nor showing any exceptions or errors

Could not resolve property - Hibernate

I have a problem with Hibernate. Im struggling with this since yesterday, it seems very easy but I have no idea why it is not working...
I have entity Login.java:
package offersmanager.model.entity;
import org.json.JSONObject;
import javax.persistence.*;
#Entity
public class Login {
#Id
#GeneratedValue
private Integer id;
#Column(nullable = false, unique = true)
String username;
#Column(nullable = false)
String password;
public Login(){
}
public Login(String username, String password){
this.username = username;
this.password = password;
}
public Login(JSONObject jsonObject) {
this.id = (Integer) jsonObject.get("id");
this.username = (String) jsonObject.get("username");
this.password = (String) jsonObject.get("password");
}
public JSONObject toJsonObject() {
JSONObject jsonObject = new JSONObject();
jsonObject.put("id", this.id);
jsonObject.put("username", this.username);
jsonObject.put("password", this.password);
return jsonObject;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
And entity TourOffice.java:
package offersmanager.model.entity;
import org.json.JSONObject;
import javax.persistence.*;
#Entity
public class TourOffice {
#Id
#GeneratedValue
private Integer id;
#Column(nullable = false)
String officeName;
#Column(nullable = false)
String eMail;
#Column(nullable = false)
String phoneNumber;
#Column(nullable = false)
String city;
#Column(nullable = false)
String zipCode;
#Column(nullable = false)
String address;
#OneToOne(cascade = {CascadeType.ALL})
#JoinColumn(name = "login_id")
Login login;
public TourOffice(){
}
public TourOffice(String officeName, String eMail, String phoneNumber, String city, String zipCode, String address) {
this.officeName = officeName;
this.eMail = eMail;
this.phoneNumber = phoneNumber;
this.city = city;
this.zipCode = zipCode;
this.address = address;
}
public TourOffice(JSONObject jsonObject) {
this.id = (Integer) jsonObject.get("id");
this.officeName = (String) jsonObject.get("officeName");
this.eMail = (String) jsonObject.get("eMail");
this.phoneNumber = (String) jsonObject.get("phoneNumber");
this.city = (String) jsonObject.get("city");
this.zipCode = (String) jsonObject.get("zipCode");
this.address = (String) jsonObject.get("address");
this.login = (new Login((JSONObject) jsonObject.get("login")));
}
public JSONObject toJsonObject() {
JSONObject jsonObject = new JSONObject();
jsonObject.put("id", this.id);
jsonObject.put("officeName", this.officeName);
jsonObject.put("eMail", this.eMail);
jsonObject.put("phoneNumber", this.phoneNumber);
jsonObject.put("city", this.city);
jsonObject.put("zipCode", this.zipCode);
jsonObject.put("address", this.address);
jsonObject.put("login", this.login == null? null : login.toJsonObject());
return jsonObject;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getOfficeName() {
return officeName;
}
public void setOfficeName(String officeName) {
this.officeName = officeName;
}
public String geteMail() {
return eMail;
}
public void seteMail(String eMail) {
this.eMail = eMail;
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getZipCode() {
return zipCode;
}
public void setZipCode(String zipCode) {
this.zipCode = zipCode;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public Login getLogin() {
return login;
}
public void setLogin(Login login) {
this.login = login;
}
}
These entities are connected with #OneToOne relation.
What I'm trying to do is to find the name of my office (officeName) with field of Login class (username).
This is my function in TourOfficeDAO.java:
public TourOffice findOfficeNameByLogin(String username) {
Criteria name = createCriteria();
name.add(Restrictions.eq("login.username", username));
return (TourOffice) name.uniqueResult();
}
It goes through TourOfficeService to my rest controller where this method is invoked. But it doesn't matter cause exeception is thrown in DAO:
could not resolve property: login.username of:
offersmanager.model.entity.TourOffice; nested exception is
org.hibernate.QueryException: could not resolve property:
login.username of: offersmanager.model.entity.TourOffice
It can't find "login.username" and have no idea why... everything seems good.
I looked for similiar topics but I haven't still managed to make this works. Any help would be appreciated.
EDIT 1:
This is my abstract class DAO.java where is the function createCriteria()
public abstract class DAO<MODEL> implements Serializable {
public abstract Class<MODEL> getEntityClass();
#Autowired
protected SessionFactory sessionFactory;
protected Session getSession(){
return sessionFactory.getCurrentSession();
}
protected Query createQuery(String query){
return getSession().createQuery(query);
}
protected SQLQuery createSQLQuery(String query){
return getSession().createSQLQuery(query);
}
protected Criteria createCriteria(){
return getSession().createCriteria(getEntityClass());
}
#SuppressWarnings("unchecked")
public MODEL findById(Integer id) {
return (MODEL) getSession().get(getEntityClass(), id);
}
public void save(MODEL entity) {
getSession().save(entity);
getSession().flush();
}
public void update(MODEL entity) {
getSession().update(entity);
getSession().flush();
}
public void saveOrUpdate(MODEL entity) {
getSession().saveOrUpdate(entity);
getSession().flush();
}
public void delete(MODEL entity) {
getSession().delete(entity);
getSession().flush();
}
public List<MODEL> list(){
Criteria criteria = createCriteria();
#SuppressWarnings("unchecked")
List<MODEL> list = criteria.list();
return list;
}
}
I think you need first to create an alias like that:
public TourOffice findOfficeNameByLogin(String username) {
Criteria name = createCriteria();
name.createAlias("login", "login");
name.add(Restrictions.eq("login.username", username));
return (TourOffice) name.uniqueResult();
}

How can my server's response quiker by perfect my code and algorithm? I want to get some suggestions

I feel my app runs slow. I use Java for my server, so except java itself,the first reason of slow run, I think, is the account of database access. Hibernate could search all attribute associate with the entity which you are using, so I think it may send a lot of SQL language when finding one entity. If there's a large concurrent happening ,the trouble will happen.
#Component("user")
#Entity
#Table(name="users")
public class User implements Serializable{
#Id
#GenericGenerator(strategy="assigned",name="idGenerator")
#GeneratedValue(generator="idGenerator")
private String client_id;
#Column(name="username")
private String username;
#Column(name="password")
private String password;
#Column(name="email")
private String email;
#Column(name="phone")
private String phone;
#Column(name="sex")
private String sex;
#Column(name="birth")
private String birth;
#Column(name="status")
public String status;
#Column(name="isonline")
private String isonline;
#Column(name="province")
private String province;
#Column(name="city")
private String city;
#ManyToOne()
#JoinColumn(name="channel_id")
private Channel channel;
#Temporal(TemporalType.TIMESTAMP)
#Column(name="created_at",updatable=true)
private Date created_at = new Date();
#Column(name="last_login_at")
private Date last_login_at;
#ManyToMany()
#JoinTable(name = "users_labels",
joinColumns = #JoinColumn(name = "client_id"),
inverseJoinColumns = #JoinColumn(name = "label_name"))
#LazyCollection(LazyCollectionOption.FALSE)
private Set<Label> labellist;
#ManyToOne()
#JoinTable(name = "user_topics",
joinColumns = #JoinColumn(name = "client_id"),
inverseJoinColumns = #JoinColumn(name = "huanxin_group_id"))
private Topic topic;
#ManyToMany()
#JoinTable(name="friends",
joinColumns=#JoinColumn(name="client_id"),
inverseJoinColumns=#JoinColumn(name="friend_id"))
#LazyCollection(LazyCollectionOption.FALSE)
private Set<User> friends;
#OneToMany(mappedBy="user")
private Set<FeedBack> feedbacks;
#ManyToMany()
#JoinTable(name="blacklist",
joinColumns=#JoinColumn(name="client_id"),
inverseJoinColumns=#JoinColumn(name="blocker_id"))
#LazyCollection(LazyCollectionOption.FALSE)
private Set<User> blacklist;
public Topic getTopic() {
return topic;
}
public void setTopic(Topic topic) {
this.topic = topic;
}
public Set<Label> getLabellist() {
return labellist;
}
public void setLabellist(Set<Label> labellist) {
this.labellist = labellist;
}
public String getClient_id() {
return client_id;
}
public void setClient_id(String client_id) {
this.client_id = client_id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getBirth() {
return birth;
}
public void setBirth(String birth) {
this.birth = birth;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getIsonline() {
return isonline;
}
public void setIsonline(String isonline) {
this.isonline = isonline;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getProvince() {
return province;
}
public void setProvince(String province) {
this.province = province;
}
public Channel getChannel() {
return channel;
}
public void setChannel(Channel channel) {
this.channel = channel;
}
public Date getCreated_at() {
return created_at;
}
public void setCreated_at(Date created_at) {
this.created_at = created_at;
}
public Date getLast_login_at() {
return last_login_at;
}
public void setLast_login_at(Date last_login_at) {
this.last_login_at = last_login_at;
}
public Set<User> getFriends() {
return friends;
}
public void setFriends(Set<User> friends) {
this.friends = friends;
}
public Set<FeedBack> getFeedbacks() {
return feedbacks;
}
public void setFeedbacks(Set<FeedBack> feedbacks) {
this.feedbacks = feedbacks;
}
public Set<User> getBlacklist() {
return blacklist;
}
public void setBlacklist(Set<User> blacklist) {
this.blacklist = blacklist;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result
+ ((client_id == null) ? 0 : client_id.hashCode());
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
User other = (User) obj;
if (client_id == null) {
if (other.client_id != null)
return false;
} else if (!client_id.equals(other.client_id))
return false;
return true;
}
#Override
public String toString() {
return "User [client_id=" + client_id + ", username=" + username
+ ", labellist=" + labellist+ "]";
}
}
Just like this, User contains Topic, Label or other Entity in future. So I think that is not possible to remove this association. How could I improve my database access to improve access speed?
Another reason influncing the app speed may be my algorithm. I use bubble sort, selection sort, and quick sort. Each sort seems to cost little time on little data. But what if the concurrent occurs? 300 users may cost only 20 msec but 300 000 I couldn't imagine.
Here is my sort code:
private static List<Map<String,Object>> sortInteger(List<Map<String,Object>> list){
int index = 0;
int max = 0;
Map<String,Object> temp = new HashMap<String, Object>();
for(int i=0;i<list.size();i++){
for(int j=0;j<list.size()-i-1;j++){
Map<String,Object> pre = (Map<String, Object>) list.get(j);
Map<String,Object> next = (Map<String, Object>) list.get(j+1);
if((Integer)pre.get("sortnum")<(Integer)next.get("sortnum")){
temp = pre;
list.set(j, next);
list.set(j+1,pre);
}
}
}
return list;
}
So in terms of above, I need some suggestion to solve my question,either theory or code.

Categories

Resources