I have trying to save values to two database table with one Struts 2.0 Action class.
I have tried it with Implementing ModelDriven But it didn't catch both VO's. Please give me a solution to catch both VO's in same struts 2.0 action class.
Code Snipper For UserVO.java
package com.sajeewi.struts.vo;
import static javax.persistence.GenerationType.IDENTITY;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;
import javax.persistence.Table;
#Entity
#Table(name = "user")
public class UserVO {
#Id
#GeneratedValue(strategy = IDENTITY)
#Column(name = "idUser", unique = true, nullable = false)
private int idUser;
#Column(name = "username", unique = true, nullable = false, length = 20)
private String username;
#Column(name = "password", unique = true, nullable = false, length = 20)
private String password;
#OneToOne(fetch = FetchType.LAZY, mappedBy = "userVO", cascade = CascadeType.ALL)
private User_DetailsVO user_DetailsVO;
#OneToMany(fetch = FetchType.LAZY, mappedBy = "userVO")
private Set<AccountVO> accountVOs;
public UserVO() {
// TODO Auto-generated constructor stub
}
public UserVO(int idUser,String username,String password){
this.idUser = idUser;
this.username = username;
this.password = password;
}
public int getIdUser() {
return idUser;
}
public void setIdUser(int idUser) {
this.idUser = idUser;
}
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 User_DetailsVO getUser_DetailsVO() {
return user_DetailsVO;
}
public void setUser_DetailsVO(User_DetailsVO user_DetailsVO) {
this.user_DetailsVO = user_DetailsVO;
}
public Set<AccountVO> getAccountVOs() {
return accountVOs;
}
public void setAccountVOs(Set<AccountVO> accountVOs) {
this.accountVOs = accountVOs;
}
}
This is for User_DetailsVO.java
package com.sajeewi.struts.vo;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToOne;
import javax.persistence.PrimaryKeyJoinColumn;
import javax.persistence.Table;
import org.hibernate.annotations.GenericGenerator;
import org.hibernate.annotations.Parameter;
#Entity
#Table(name="user_details")
public class User_DetailsVO {
#Id
#Column(name = "User_idUser", unique = true, nullable = false)
#GeneratedValue(generator = "generator")
#GenericGenerator(name = "generator", strategy = "foreign", parameters = #Parameter(name = "property", value = "userVO"))
private int User_idUser;
#OneToOne(fetch = FetchType.LAZY)
#PrimaryKeyJoinColumn
private UserVO userVO;
#Column(name = "contact1", nullable = false, length = 15)
private String contact1;
#Column(name = "contact2", nullable = false, length = 15)
private String contact2;
#Column(name = "email", nullable = false, length = 50)
private String email;
#Column(name = "add1", nullable = false, length = 100)
private String add1;
#Column(name = "add2", nullable = false, length = 100)
private String add2;
#Column(name = "city", nullable = false, length = 50)
private String city;
public User_DetailsVO() {
// TODO Auto-generated constructor stub
}
public User_DetailsVO(UserVO userVO,String contact1,String contact2,String email,String add1,String add2,String city){
this.userVO = userVO;
this.contact1 = contact1;
this.contact2 = contact2;
this.email = email;
this.add1= add1;
this.add2 = add2;
this.city = city;
}
public int getUser_idUser() {
return User_idUser;
}
public void setUser_idUser(int user_idUser) {
User_idUser = user_idUser;
}
public UserVO getUserVO() {
return userVO;
}
public void setUserVO(UserVO userVO) {
this.userVO = userVO;
}
public String getContact1() {
return contact1;
}
public void setContact1(String contact1) {
this.contact1 = contact1;
}
public String getContact2() {
return contact2;
}
public void setContact2(String contact2) {
this.contact2 = contact2;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getAdd1() {
return add1;
}
public void setAdd1(String add1) {
this.add1 = add1;
}
public String getAdd2() {
return add2;
}
public void setAdd2(String add2) {
this.add2 = add2;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
}
This is the User Action Class
package com.sajeewi.struts.action;
import java.util.ArrayList;
import java.util.List;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import com.sajeewi.struts.dao.UserDAO;
import com.sajeewi.struts.dao.impl.UserDAOImpl;
import com.sajeewi.struts.vo.UserVO;
import com.sajeewi.struts.vo.User_DetailsVO;
#SuppressWarnings({ "serial" })
public class UserAction extends ActionSupport implements ModelDriven<Object>{
UserVO userVO = new UserVO();
User_DetailsVO detailsVO = new User_DetailsVO();
List<UserVO> userList = new ArrayList<UserVO>();
UserDAO userDAO = new UserDAOImpl();
public List<UserVO> getUserList() {
return userList;
}
public void setUserList(List<UserVO> userList) {
this.userList = userList;
}
public UserDAO getUserDAO() {
return userDAO;
}
public void setUserDAO(UserDAO userDAO) {
this.userDAO = userDAO;
}
public UserVO getUserVO() {
return userVO;
}
public void setUserVO(UserVO userVO) {
this.userVO = userVO;
}
public User_DetailsVO getDetailsVO() {
return detailsVO;
}
public void setDetailsVO(User_DetailsVO detailsVO) {
this.detailsVO = detailsVO;
}
public String addUser(){
// userDAO.saveUser(this.userVO);
// userList = null;
// try {
// userList = userDAO.searchAllUsers();
// } catch (Exception e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
System.out.println(this.userVO);
System.out.println(this.detailsVO);
return SUCCESS;
}
public Object getModel() {
return userVO;
}
}
Jsp View
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib prefix="s" uri="/struts-tags"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>User</title>
</head>
<body>
<s:div>
<h2>Registration With Struts 2.0</h2>
<s:form action="addUser" method="POST">
<s:div>
<h4>Enter User Credentials</h4>
<s:textfield name="username" label="Username"></s:textfield>
<s:password name="password" label="Password"></s:password>
</s:div>
<br>
<s:textfield name="contact1" label="Contact1 "></s:textfield>
<s:textfield name="contact2" label="Contact2 "></s:textfield>
<s:textfield name="email" label="E-Mail "></s:textfield>
<s:textfield name="add1" label="Address Line 1 "></s:textfield>
<s:textfield name="add2" label="Address Line 2 "></s:textfield>
<s:textfield name="city" label="City "></s:textfield>
<br>
<s:submit name="Save" value="Save"></s:submit>
</s:form>
</s:div>
</body>
</html>
I want to save to both tables with same form
Thanks
OK, so you have a separate table to for storing user-info but all that info is being read from single form. In that case, its simple.
Dont go for model-driven as all form-fields are not present in single class else you can have a bean class for the same (I don't recommend it).Populate the corresponding values in the two class objects UserVO and User_DetailsVO using getters n setters in action class.
Now all you do is:
Session session = SessionFactory.openSession();
session.save(userVO);
int savedId = userVO.getIdUser();
detailsVO. setUser_idUser(savedId);
session.save(detailsVO);
session.close();
I am unable to guess in your table which one is primary key and which is foreign key. So save the object which is primary and then save the other object which have FK.
Got a solution. I have changed my JSP like this
Before
<s:textfield name="username" label="Username"></s:textfield>
Now
<s:textfield name="userVO.username" label="Username"></s:textfield>
All i have do is add VO name to the textfield name then it automatically catch all the data in the action class for both UserVO and User_DetailsVO
Thanks
Related
I'm new spring boot and making todo application.
I'm trying to display logged in user's todo but it results in all todos are displayed.
Does anyone help?
TodoRepository
package com.portfoilo.fullstackbackend.Repository;
import com.portfoilo.fullstackbackend.Model.Todo;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import java.util.List;
#Repository
public interface TodoRepository extends JpaRepository<Todo, Integer> {
#Query(value = "SELECT * FROM todos WHERE user_id = :id", nativeQuery = true)
List<Todo> find(#Param("id") Integer id);
}
TodoController
package com.portfoilo.fullstackbackend.Controller;
import com.portfoilo.fullstackbackend.Model.Todo;
import com.portfoilo.fullstackbackend.Model.User;
import com.portfoilo.fullstackbackend.Model.UserDetailsImpl;
import com.portfoilo.fullstackbackend.Repository.TodoRepository;
import com.portfoilo.fullstackbackend.Service.TodoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
#Controller
public class TodoController {
#Autowired
TodoRepository todoRepository;
#Autowired
TodoService todoService;
#GetMapping("/todo/{id}")
public String home(#PathVariable("id")Integer id, Model model, HttpServletResponse httpServletResponse, #AuthenticationPrincipal UserDetailsImpl userDetails, User user)
{
System.out.println(userDetails.getUsername());
System.out.println(user.getId());
httpServletResponse.addCookie(new Cookie("user_id", user.getId().toString()));
List<Todo> list = todoRepository.find(id);
model.addAttribute("list", list);
model.addAttribute("todo", new Todo());
return "home";
}
public String showCookie(#CookieValue("user_id") String cookieValue) {
System.out.println(cookieValue);
return "home";
}
#PostMapping("/todo/{id}")
public String createTodo(#Validated Todo todo, BindingResult result, Model model) {
todoService.addTodo(todo);
return "redirect:/todo/{id}";
}
}
Todo.java
package com.portfoilo.fullstackbackend.Model;
import com.portfoilo.fullstackbackend.SignupForm;
import lombok.Data;
import javax.persistence.*;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import java.util.Date;
#Entity
#Data
#Table(name = "todos")
public class Todo {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
#Column(name = "user_id")
private Integer user_id;
#NotNull
#NotBlank
#Column(name = "title")
private String title;
#NotNull
#NotBlank
#Column(name = "description")
private String description;
#Column(name = "due_date")
private Date due_date;
#Column(name = "priority")
private Integer priority;
#ManyToOne
#JoinColumn(name = "user_id" ,insertable = false, updatable = false)
private User user;
}
User.java
package com.portfoilo.fullstackbackend.Model;
import javax.persistence.*;
import java.util.ArrayList;
import java.util.List;
#Entity
#Table(name = "users")
public class User {
#Id
#Column(name = "id")
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
#Column(name = "email")
private String email;
#Column(name = "password")
private String password;
#Column(name = "authority")
private String authority;
#OneToMany(mappedBy = "user")
private List<Todo> todos;
public User(String email, String password, String authority) {
this.email = email;
this.password = password;
this.authority = authority;
}
public User() {
}
public Integer getId() {
return id;
}
public void setId(Integer 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 getAuthority() {
return authority;
}
public void setAuthority(String authority) {
this.authority = authority;
}
public List<Todo> getTodos() {
return todos;
}
public void setTodos(List<Todo> todos) {
this.todos = todos;
}
}
Home.html
<html xmlns:th="http://www.thymeleaf.org" xmlns="http://www.w3.org/1999/html">
<head>
<meta charset="UTF-8">
<link th:href="#{/css/home.css}" rel="stylesheet"/>
<title>Todo</title>
</head>
<body>
<div th:text="'Hello ' + ${#authentication.name}"></div>
<h1>Todo</h1>
<h2>Add</h2>
<div>
<form method="post" th:action="#{/todo}" th:object="${todo}">
<p th:errors="*{title}" class="todo-error-message"></p>
<input th:field="*{title}" class="add-input" type="text" placeholder="title">
<input th:field="*{description}" class="add-input" type="text"
placeholder="details">
<input th:field="*{due_date}" class="add-input-third" type="text">
<br/>
<div class="add-form">
<span>Priority</span>
<input type="radio" name="priority" value="3" checked>大
<input type="radio" name="priority" value="2">中
<input type="radio" name="priority" value="1">小<br/>
</div>
<button type="submit" class="add-btn">Add</button>
</form>
</div>
<h2>List</h2>
<div>
<tr th:each="list:${list}">
<td th:text="${list.title}">
<td th:text="${list.user_id}">
</tr>
</div>
<form th:action="#{/logout}" method="post">
<button class="logout-button" type="submit" value="logout">logout</button>
</form>
</body>
</html>
I thought TodoRepository's query is may be wrong but I couldn't find something like correct answer.
I would appreciate it if you could help...!
I am making authorization for a web application. And I an faced witw problem. I can not use Getters and Setters. Namely setActive ans setRole. And I can not create variable UserFromDb.
RegistrationController.java
import com.Vova.Restart.Models.Role;
import com.Vova.Restart.repo.UserRepo;
import org.springframework.security.core.userdetails.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import java.util.Collections;
import java.util.Map;
#Controller
public class RegistrationController {
#Autowired
private UserRepo userRepo;
#GetMapping("/registration")
public String registration() {
return "registration";
}
#PostMapping("/registration")
public String addUser (User user, Map<String, Object> model) {
userFromDb = userRepo.findByUsername(user.getUsername());
if (userFromDb != null) {
model.put("message", "User exists!");
return "registration";
}
user.setActive(true);
user.setRole(Collections.singleton(Role.USER));
return "redirect:/login";
}
}
User.java
import javax.persistence.*;
import java.util.Set;
#Entity
#Table(name = "User")
public class User {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String username, password;
private boolean active;
#ElementCollection(targetClass = Role.class, fetch = FetchType.EAGER)
#CollectionTable(name = "userRole", joinColumns = #JoinColumn(name = "userId"))
#Enumerated(EnumType.STRING)
private Set<Role> roles;
public Long getId() {
return id;
}
public void setId(Long 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;
}
public boolean isActive() {
return active;
}
public void setActive(boolean active) {
this.active = active;
}
public Set<Role> getRoles() {
return roles;
}
public void setRoles(Set<Role> roles) {
this.roles = roles;
}
public void setRole(Set<Object> singleton) {
}
}
I tried to use import com.Vova.Restart.Models.User instead import org.springframework.security.core.userdetails.User and this error has gone but i get another problem Not a managed type: class org.springframework.security.core.userdetails.User. I think this is wrong imort. How can i solve it?
I'm creating a dynamic menu using spring and hibernate based on user roles. It works fine and menu is getting generated. but the relationship between menu and submenu doesn't work properly. I want only submenus which has roles assigned to them. but it contains all the submenus.
My POJOs are like below.
Menu.java
package com.pmc.domain;
import java.io.Serializable;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Transient;
import org.hibernate.annotations.Fetch;
#Entity
#Table(name="menu", catalog="test")
public class Menu implements Serializable{
#Id
#Column(name = "menu_item_id")
private Integer menuId;
#ManyToMany(cascade={CascadeType.ALL})
#JoinTable(name="MENU_ROLES",
joinColumns={#JoinColumn(name="menu_item_id")},
inverseJoinColumns={#JoinColumn(name="user_role_id")})
private List<UserRole> userRoles;
#Column(name = "label", length = 100)
private String label;
#Column(name = "link", length = 100)
private String link;
#ManyToOne(cascade={CascadeType.ALL})
#JoinColumn(name = "parent")
private Menu parent;
#OneToMany(mappedBy="parent",fetch = FetchType.EAGER)
private List<Menu> submenus;
public Integer getMenuId() {
return menuId;
}
public void setMenuId(Integer menuId) {
this.menuId = menuId;
}
public List<UserRole> getUserRoles() {
return userRoles;
}
public void setUserRoles(List<UserRole> userRoles) {
this.userRoles = userRoles;
}
public String getLabel() {
return label;
}
public void setLabel(String label) {
this.label = label;
}
public String getLink() {
return link;
}
public void setLink(String link) {
this.link = link;
}
public Menu getParent() {
return parent;
}
public void setParent(Menu parent) {
this.parent = parent;
}
public List<Menu> getSubmenus() {
return submenus;
}
public void setSubmenus(List<Menu> submenus) {
this.submenus = submenus;
}
}
UserRole.java
package com.pmc.domain;
import static javax.persistence.GenerationType.IDENTITY;
import java.util.List;
import java.util.Set;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.UniqueConstraint;
#Entity
#Table (name = "roles", catalog = "test")
public class UserRole {
private Integer userRoleId;
private Set<User> users;
private String role;
private List<Menu> menus;
public UserRole() {
}
public UserRole(Set<User> users, String role) {
this.users = users;
this.role = role;
}
#Id
#GeneratedValue(strategy = IDENTITY)
#Column(name = "user_role_id",
unique = true, nullable = false)
public Integer getUserRoleId() {
return this.userRoleId;
}
public void setUserRoleId(Integer userRoleId) {
this.userRoleId = userRoleId;
}
#ManyToMany(fetch = FetchType.LAZY)
#JoinTable(name="USER_ROLES",
joinColumns={#JoinColumn(name="user_role_id")},
inverseJoinColumns={#JoinColumn(name="username")})
public Set<User> getUsers() {
return this.users;
}
public void setUsers(Set<User> users) {
this.users = users;
}
#Column(name = "role", nullable = false, length = 45)
public String getRole() {
return this.role;
}
public void setRole(String role) {
this.role = role;
}
#ManyToMany(mappedBy="userRoles",fetch = FetchType.EAGER)
public List<Menu> getMenus() {
return menus;
}
public void setMenus(List<Menu> menus) {
this.menus = menus;
}
}
User.java
package com.pmc.domain;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Id;
import javax.persistence.ManyToMany;
import javax.persistence.OneToMany;
import javax.persistence.Table;
#Entity
#Table(name="users", catalog="test")
public class User {
private String username;
private String password;
private boolean enabled;
private Set<UserRole> userRole = new HashSet<UserRole>(0);
public User() {
}
public User(String username, String password, boolean enabled) {
this.username = username;
this.password = password;
this.enabled = enabled;
}
public User(String username, String password,
boolean enabled, Set<UserRole> userRole) {
this.username = username;
this.password = password;
this.enabled = enabled;
this.userRole = userRole;
}
#Id
#Column(name = "username", unique = true,
nullable = false, length = 45)
public String getUsername() {
return this.username;
}
public void setUsername(String username) {
this.username = username;
}
#Column(name = "password",
nullable = false, length = 60)
public String getPassword() {
return this.password;
}
public void setPassword(String password) {
this.password = password;
}
#Column(name = "enabled", nullable = false)
public boolean isEnabled() {
return this.enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
#ManyToMany(mappedBy = "users")
public Set<UserRole> getUserRole() {
return this.userRole;
}
public void setUserRole(Set<UserRole> userRole) {
this.userRole = userRole;
}
}
my query is like this.
select menu from User user, IN (user.userRole) roles, IN(roles.menus) menu where user.username = ?
It gives all the required menus with proper roles to the user. But the list of submenus in each menu is not reflected according to the roles.
Can you please help on this?
Thanks
I am trying to use Hibernate annotations for writing a model class for my database tables.
I have two tables each having a primary key User and ChartDetails.
package com.winnow.springservice.domain;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
//User Entity class mapped with hibernate
#Entity
#Table(name="User")
#SuppressWarnings(value = { "all" })
public class User implements Serializable
{
#Id
#Column(name="user_id")
public String user_Id;
#Column(name="user_name")
public String userName;
public String password;
#Column(name="last_login")
public String last_Login;
#Column(name="role_id")
public int role_Id;
public int status;
public String getUser_Id() {
return user_Id;
}
public void setUser_Id(String user_Id) {
this.user_Id = user_Id;
}
public String getLast_Login() {
return last_Login;
}
public void setLast_Login(String last_Login) {
this.last_Login = last_Login;
}
public int getRole_Id() {
return role_Id;
}
public void setRole_Id(int role_Id) {
this.role_Id = role_Id;
}
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
System.out.println("username"+userName);
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password)
{
System.out.println("password "+password);
this.password = password;
}
}
Chart details
package com.winnow.springservice.domain;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="Chart_Details")
#SuppressWarnings(value = { "all" })
public class ChartDetails implements Serializable
{
#Id
#Column(name="chart_id")
public int chartId;
#Id
#Column(name="chart_type_id")
public int chartTypeId;
#Column(name="chart_name")
public String chartName;
#Column(name="x_axis")
public String x_axis;
#Column(name="y_axis")
public String y_axis;
#Column(name="z_axis")
public int z_axis;
#Column(name="chart_filter_id")
public int chartFilterId;
#Column(name="is_data_table")
public boolean isDataTable;
#Column(name="dataset_id")
public int datasetId;
#Column(name="user_id")
public int userId;
#Column(name="project_id")
public int projectId;
}
And I have one more table – ChartsStarredBy – which has userId and chart_id as foreign keys from the above two tables.
But I am unable to find how I can reference these constraints in the ChartsStarredBy table.
package com.winnow.springservice.domain;
import java.io.Serializable;
import java.util.Date;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
#Entity
#Table(name="Chart_Starred_By")
#SuppressWarnings(value = { "all" })
public class ChartsStarredBy implements Serializable
{
#Id
public int id;
#Temporal(TemporalType.DATE)
public Date starred_date;
#ManyToOne
#JoinColumn(name = "FK_chart_id4")
private ChartDetails chart_details;
#ManyToOne
#JoinColumn(name = "FK_user_id4")
private User user;
public Date getStarred_date()
{
return starred_date;
}
public void setStarred_date(Date starred_date)
{
this.starred_date = starred_date;
}
public User getUser()
{
return user;
}
public void setUser(User user)
{
this.user = user;
}
public ChartDetails getChart_details() {
return chart_details;
}
public void setChart_details(ChartDetails chart_details) {
this.chart_details = chart_details;
}
}
Please help me achieve this? Thanks in advance.
First of all you should create an integer id for User table which is primary key. Here in your code you creating it as String type.
You are doing wrong here
#ManyToOne
#JoinColumn(name = "FK_chart_id4")
private ChartDetails chart_details;
#ManyToOne
#JoinColumn(name = "FK_user_id4")
private User user;
You have IDs in User table & ChartDetails table as
#Id
#Column(name="user_id")
public String user_Id;
AND
#Id
#Column(name="chart_id")
public int chartId;
So when you refer to id of another class you should give name of that id in #JoinColumn. Just like this
#ManyToOne
#JoinColumn(name = "chartId")
private ChartDetails chart_details;
#ManyToOne
#JoinColumn(name = "user_Id")
private User user;
You can also use #ForeignKey(name = "user_Id") annotation from Hibernate like this
#ManyToOne
#ForeignKey(name = "user_Id")
private User user;
Example tutorial :- Hibernate One To Many Annotation Tutorial
I have finished my website using Spring MVC with Maven. Now I want to deploy it to CloudBees for testing. Every settings(connecting to db, code logic,...) are ok but when I start the application, I'm facing a problem about indexing in Hibernate Search. It looks like I don't have permission to create index directory in Cloud Bees Tomcat 7 server. Below is the stack trace:
Caused by: org.hibernate.search.SearchException: Unable to initialize directory provider: org.appfuse.model.User
at org.hibernate.search.store.impl.DirectoryProviderFactory.createDirectoryProvider(DirectoryProviderFactory.java:87)
at org.hibernate.search.indexes.impl.DirectoryBasedIndexManager.createDirectoryProvider(DirectoryBasedIndexManager.java:216)
at org.hibernate.search.indexes.impl.DirectoryBasedIndexManager.initialize(DirectoryBasedIndexManager.java:89)
at org.hibernate.search.indexes.impl.IndexManagerHolder.createDirectoryManager(IndexManagerHolder.java:241)
... 53 more
Caused by: org.hibernate.search.SearchException: Unable to create index directory: /mnt/genapp/apps/3926c2d0/fsgetter/index for index org.appfuse.model.User
at org.hibernate.search.store.impl.DirectoryProviderHelper.makeSanityCheckedDirectory(DirectoryProviderHelper.java:261)
at org.hibernate.search.store.impl.DirectoryProviderHelper.getVerifiedIndexDir(DirectoryProviderHelper.java:243)
at org.hibernate.search.store.impl.FSDirectoryProvider.initialize(FSDirectoryProvider.java:66)
at org.hibernate.search.store.impl.DirectoryProviderFactory.createDirectoryProvider(DirectoryProviderFactory.java:84)
... 56 more
Below is my POJO need to index:
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import javax.persistence.Column;
import javax.persistence.Embedded;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.Table;
import javax.persistence.Transient;
import javax.persistence.Version;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;
import org.apache.commons.lang.builder.ToStringBuilder;
import org.apache.commons.lang.builder.ToStringStyle;
import org.codehaus.jackson.annotate.JsonIgnore;
import org.hibernate.annotations.Fetch;
import org.hibernate.annotations.FetchMode;
import org.hibernate.search.annotations.Analyze;
import org.hibernate.search.annotations.DocumentId;
import org.hibernate.search.annotations.Field;
import org.hibernate.search.annotations.Indexed;
import org.hibernate.search.annotations.IndexedEmbedded;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
#Entity
#Table(name = "app_user")
#Indexed
#XmlRootElement
public class User extends BaseObject implements Serializable, UserDetails {
private static final long serialVersionUID = 3832626162173359411L;
private Long id;
private String username; // required
private String password; // required
private String confirmPassword;
private String passwordHint;
private String firstName; // required
private String lastName; // required
private String email; // required; unique
private String phoneNumber;
private String website;
private Address address = new Address();
private Integer version;
private Set<Role> roles = new HashSet<Role>();
private boolean enabled;
private boolean accountExpired;
private boolean accountLocked;
private boolean credentialsExpired;
private int freeLink;
/**
* Default constructor - creates a new instance with no values set.
*/
public User() {
}
/**
* Create a new instance and set the username.
*
* #param username login name for user.
*/
public User(final String username) {
this.username = username;
}
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#DocumentId
public Long getId() {
return id;
}
#Column(nullable = false, length = 50, unique = true)
#Field
public String getUsername() {
return username;
}
#Column(nullable = false)
#XmlTransient
#JsonIgnore
public String getPassword() {
return password;
}
#Transient
#XmlTransient
#JsonIgnore
public String getConfirmPassword() {
return confirmPassword;
}
#Column(name = "password_hint")
#XmlTransient
public String getPasswordHint() {
return passwordHint;
}
#Column(name = "first_name", nullable = false, length = 50)
#Field
public String getFirstName() {
return firstName;
}
#Column(name = "last_name", nullable = false, length = 50)
#Field
public String getLastName() {
return lastName;
}
#Column(nullable = false, unique = true)
#Field
public String getEmail() {
return email;
}
#Column(name = "phone_number")
#Field(analyze= Analyze.NO)
public String getPhoneNumber() {
return phoneNumber;
}
#Field
public String getWebsite() {
return website;
}
/**
* Returns the full name.
*
* #return firstName + ' ' + lastName
*/
#Transient
public String getFullName() {
return firstName + ' ' + lastName;
}
#Embedded
#IndexedEmbedded
public Address getAddress() {
return address;
}
#ManyToMany(fetch = FetchType.EAGER)
#Fetch(FetchMode.SELECT)
#JoinTable(
name = "user_role",
joinColumns = { #JoinColumn(name = "user_id") },
inverseJoinColumns = #JoinColumn(name = "role_id")
)
public Set<Role> getRoles() {
return roles;
}
/**
* Convert user roles to LabelValue objects for convenience.
*
* #return a list of LabelValue objects with role information
*/
#Transient
public List<LabelValue> getRoleList() {
List<LabelValue> userRoles = new ArrayList<LabelValue>();
if (this.roles != null) {
for (Role role : roles) {
// convert the user's roles to LabelValue Objects
userRoles.add(new LabelValue(role.getName(), role.getName()));
}
}
return userRoles;
}
/**
* Adds a role for the user
*
* #param role the fully instantiated role
*/
public void addRole(Role role) {
getRoles().add(role);
}
/**
* #return GrantedAuthority[] an array of roles.
* #see org.springframework.security.core.userdetails.UserDetails#getAuthorities()
*/
#Transient
public Set<GrantedAuthority> getAuthorities() {
Set<GrantedAuthority> authorities = new LinkedHashSet<GrantedAuthority>();
authorities.addAll(roles);
return authorities;
}
#Version
public Integer getVersion() {
return version;
}
/**
* #return the freeLink
*/
#Column(name = "freeLink")
public int getFreeLink() {
return freeLink;
}
#Column(name = "account_enabled")
public boolean isEnabled() {
return enabled;
}
#Column(name = "account_expired", nullable = false)
public boolean isAccountExpired() {
return accountExpired;
}
/**
* #see org.springframework.security.core.userdetails.UserDetails#isAccountNonExpired()
* #return true if account is still active
*/
#Transient
public boolean isAccountNonExpired() {
return !isAccountExpired();
}
#Column(name = "account_locked", nullable = false)
public boolean isAccountLocked() {
return accountLocked;
}
/**
* #see org.springframework.security.core.userdetails.UserDetails#isAccountNonLocked()
* #return false if account is locked
*/
#Transient
public boolean isAccountNonLocked() {
return !isAccountLocked();
}
#Column(name = "credentials_expired", nullable = false)
public boolean isCredentialsExpired() {
return credentialsExpired;
}
/**
* #see org.springframework.security.core.userdetails.UserDetails#isCredentialsNonExpired()
* #return true if credentials haven't expired
*/
#Transient
public boolean isCredentialsNonExpired() {
return !credentialsExpired;
}
public void setId(Long id) {
this.id = id;
}
public void setUsername(String username) {
this.username = username;
}
public void setPassword(String password) {
this.password = password;
}
public void setConfirmPassword(String confirmPassword) {
this.confirmPassword = confirmPassword;
}
public void setPasswordHint(String passwordHint) {
this.passwordHint = passwordHint;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public void setEmail(String email) {
this.email = email;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public void setWebsite(String website) {
this.website = website;
}
public void setAddress(Address address) {
this.address = address;
}
public void setRoles(Set<Role> roles) {
this.roles = roles;
}
public void setVersion(Integer version) {
this.version = version;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
public void setAccountExpired(boolean accountExpired) {
this.accountExpired = accountExpired;
}
public void setAccountLocked(boolean accountLocked) {
this.accountLocked = accountLocked;
}
public void setCredentialsExpired(boolean credentialsExpired) {
this.credentialsExpired = credentialsExpired;
}
/**
* #param freeLink the freeLink to set
*/
public void setFreeLink(int freeLink) {
this.freeLink = freeLink;
}
/**
* {#inheritDoc}
*/
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof User)) {
return false;
}
final User user = (User) o;
return !(username != null ? !username.equals(user.getUsername()) : user.getUsername() != null);
}
/**
* {#inheritDoc}
*/
public int hashCode() {
return (username != null ? username.hashCode() : 0);
}
/**
* {#inheritDoc}
*/
public String toString() {
ToStringBuilder sb = new ToStringBuilder(this, ToStringStyle.DEFAULT_STYLE)
.append("username", this.username)
.append("enabled", this.enabled)
.append("accountExpired", this.accountExpired)
.append("credentialsExpired", this.credentialsExpired)
.append("accountLocked", this.accountLocked);
if (roles != null) {
sb.append("Granted Authorities: ");
int i = 0;
for (Role role : roles) {
if (i > 0) {
sb.append(", ");
}
sb.append(role.toString());
i++;
}
} else {
sb.append("No Granted Authorities");
}
return sb.toString();
}
}
Update application-context.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd"
default-lazy-init="true">
<!-- Activates scanning of #Autowired -->
<context:annotation-config />
<!-- Activates scanning of #Repository and #Service -->
<context:component-scan base-package="com.giangnt" />
<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="configLocation" value="classpath:hibernate.cfg.xml" />
<property name="hibernateProperties">
<value>
hibernate.search.default.indexBase=fsgetter/index
hibernate.dialect=${hibernate.dialect}
</value>
</property>
</bean>
</beans>
I want to ask how to create index directory in Cloud Bees tomcat 7 server so that my web application can publish for testing?
Filesystem isn't persistent, so for your safety it's write proteceted but java.io.tmpDir - as you can use this one to store whatever temp file you need, but have to know it will disappear on next deployment / restart