My English is not very well, so sorry for mistakes.
I'am using a Spring, Spring MVC, Hibernate, Spring Data.
I have two entities Customer and CustomerDetails I would like to connect/bind them.
I'am using #OneToOne annotation, but I have no idea how to set a customer for CusomerDetails and vice versa. I found that I should create Customer and CustomerDetails in controller, and there connect them, but it is not working and I think that it is a bad approach. Anyone knows How should it looks?
Thanks for help.
Customer class:
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.OneToOne;
import javax.persistence.Table;
#Entity
#Table(name="customer")
public class Customer {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name="customer_id")
private int id;
#Column(name="name")
private String name;
#Column(name="email")
private String email;
#Column(name="address")
private String address;
#OneToOne(cascade=CascadeType.ALL)
private CustomerDetails customerDetails;
public Customer() {
}
public Customer(CustomerDetails customerDetails)
{
this.customerDetails=customerDetails;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public CustomerDetails getCustomerDetails() {
return customerDetails;
}
public void setCustomerDetails(CustomerDetails customerDetails) {
this.customerDetails = customerDetails;
}
#Override
public String toString() {
return "Customer [id=" + id + ", name=" + name + ", email=" + email + ", address=" + address
+ ", customerDetails=" + customerDetails + "]";
}
}
CustomerDetails:
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.JoinColumn;
import javax.persistence.OneToOne;
import javax.persistence.Table;
#Entity
#Table(name="customer_details")
public class CustomerDetails {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
private int id;
#Column(name="surname")
private String lastName;
#Column(name="number")
private int number;
#OneToOne(cascade= {CascadeType.DETACH,CascadeType.MERGE,CascadeType.PERSIST,CascadeType.REFRESH})
private Customer customer;
public CustomerDetails() {
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public int getNumber() {
return number;
}
public void setNumber(int number) {
this.number = number;
}
public Customer getCustomer() {
return customer;
}
public void setCustomer(Customer customer) {
this.customer = customer;
}
#Override
public String toString() {
return "CustomerDetails [id=" + id + ", lastName=" + lastName + ", number=" + number + ", customer=" + customer
+ "]";
}
}
Services:
import java.util.List;
import com.firstapp.entity.Customer;
public interface CustomerService {
public List<Customer>getCustomers();
public Customer getCustomer(int id);
public void saveCustomer(Customer customer);
public void deleteCustomer(int id);
public List<Customer>search(String keyword);
}
public interface CustomerDetailsService {
public List<CustomerDetails> getCustomers();
public CustomerDetails getCustomer(int id);
public void saveCustomer(CustomerDetails customer);
public void deleteCustomer(int id);
}
#Service
public class CustomerServiceImpl implements CustomerService {
#Autowired
private CustomerRepository repo;
public List<Customer> getCustomers() {
return repo.findAll();
}
public Customer getCustomer(int id) {
Optional<Customer>result= repo.findById(id);
return result.get();
}
public void saveCustomer(Customer customer) {
repo.save(customer);
}
public void deleteCustomer(int id) {
repo.deleteById(id);
}
public List<Customer>search(String keyword)
{
return repo.search(keyword);
}
}
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.firstapp.entity.CustomerDetails;
import com.firstapp.repository.CustomerDetailsRepository;
#Service
public class CustomerDetailsServiceImpl implements CustomerDetailsService{
#Autowired
private CustomerDetailsRepository repo;
public List<CustomerDetails> getCustomers() {
return repo.findAll();
}
public CustomerDetails getCustomer(int id) {
return repo.findById(id).get();
}
public void saveCustomer(CustomerDetails customer) {
repo.save(customer);
}
public void deleteCustomer(int id) {
repo.deleteById(id);
}
}
Repositories:
import java.util.List;
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 com.firstapp.entity.Customer;
#Repository
public interface CustomerRepository extends JpaRepository<Customer, Integer> {
#Query(value="SELECT c from Customer c where c.name LIKE '%'|| :keyword || '%'"
+ "OR c.email LIKE '%'|| :keyword || '%'"
+ "OR c.address LIKE '%'|| :keyword || '%'")
public List<Customer>search(#Param("keyword")String keyword);
}
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import com.firstapp.entity.CustomerDetails;
#Repository
public interface CustomerDetailsRepository extends JpaRepository<CustomerDetails, Integer> {
}
My controller:
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import com.firstapp.entity.Customer;
import com.firstapp.entity.CustomerDetails;
import com.firstapp.service.CustomerDetailsService;
import com.firstapp.service.CustomerDetailsServiceImpl;
import com.firstapp.service.CustomerService;
import com.firstapp.service.CustomerServiceImpl;
#Controller
#RequestMapping("/customer")public class CustomerController {
#Autowired
private CustomerService service;
#Autowired
private CustomerDetailsService serviceCD;
#GetMapping("/home")public String home(Model model)
{
List<Customer>customers=service.getCustomers();
model.addAttribute("message","Hello from Spring MVC"); model.addAttribute("customers",customers);
return "home-page";
}
#GetMapping("/showForm")
public String showForm(Map<String,Object>model)
{
Customer customer=new Customer();
CustomerDetails cd=new CustomerDetails();
customer.setCustomerDetails(cd);
model.put("customer",new Customer());
model.put("customerDetails", cd);
return "new-customer";
}
#PostMapping("/add")
public String addCustomer(#ModelAttribute("customer") Customer customer)
{
service.saveCustomer(customer);
return "redirect:/customer/addDetails";
}
#RequestMapping("/addDetails")
public String addCustomerDetails(#ModelAttribute("customerDetails") CustomerDetails customerDt)
{
serviceCD.saveCustomer(customerDt);
return "redirect:/customer/home";
}
#GetMapping("/edit")
public String editCustomer(#RequestParam int id, Model model)
{
Customer customer=service.getCustomer(id);
model.addAttribute("customer",customer);
return "edit-customer";
}
#GetMapping("/delete")
public String deleteCustomer(#RequestParam int id)
{
service.deleteCustomer(id);
return "redirect:/customer/home";
}
#GetMapping("/search")
public String search(#RequestParam String keyword,Model model)
{
List<Customer>customers=service.search(keyword);
model.addAttribute("customers",customers);
return "search-page";
}
}
my jsp:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1" isELIgnored="false"%>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Customer registration</title>
</head>
<body>
<div align="center">
<h2>New Customer</h2>
<form:form action="add" method="post" modelAttribute="customer">
<table>
<tr>
<td>Name:</td>
<td><form:input path="name"/></td>
</tr>
<tr>
<td>E-mail:</td>
<td><form:input path="email"/></td>
</tr>
<tr>
<td>Address:</td>
<td><form:input path="address"/></td>
</tr>
<tr>
<td></td><td><input type="submit" value="Submit"/></td>
</tr>
</table>
</form:form>
</div>
</body>
</html>
Set the CustomerDetails for Customer:
customer.setCustomerDetail(customerDetail);
customerDetail.setCustomer(customer);
It's enough. Spring JPA automatically sets references and id's between table entities.
In additional try to change model layer:
1) First what you should to change - add the mappedBy parameter with table name into '#OneToOne'
2) Use #JoinColumn for one of entity:
for Customer:
#OneToOne(mappedBy = "customer")
#JoinColumn(name = "customer_details_id", referencedColumnName = "id")
for CustomerDetails:
#OneToOne(mappedBy = "customer_detail")
in additional: try to save CustomerDetail entity into table after creating, but before saving a Customer.
PS
Does no matter technically where are you create entities - it is just patterns and SOLID principals.
All parameters in #OneToOne and #JoinColumn should be named as fields in entity and as tables. Once I had a very difficult and long resolving with this issue. So be precise.
Related
I have a simple Quarkus project and want to show the data in an Angular table with HttpClient. I also have a CORS Filter. Anyway, I get the following error:
Angular table with no date, HttpErrorResponse Status 0
service.ts
import { HttpClient } from '#angular/common/http';
import { Injectable } from '#angular/core';
import { Observable } from 'rxjs';
import { School } from './model/school';
#Injectable({
providedIn: 'root'
})
export class SchoolService {
url = "localhost:8080/school"
constructor(public http: HttpClient) { }
getAll(): Observable<School[]> {
return this.http.get<School[]>(this.url);
}
getById(id: number): Observable<School> {
const url = "locahlost:8080/school/{id}";
return this.http.get<School>(url);
}
}
ts of component
import { Component, OnInit } from '#angular/core';
import { School } from '../model/school';
import { SchoolService } from '../school.service';
#Component({
selector: 'app-dashboard',
templateUrl: './dashboard.component.html',
styleUrls: ['./dashboard.component.css']
})
export class DashboardComponent implements OnInit {
schools: School[] = [];
constructor(public schoolService: SchoolService) { }
ngOnInit(): void {
this.schoolService.getAll().subscribe(e => {
this.schools = e;
});
}
}
html
<table>
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Street</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let school of schools">
<td>{{school.id}}</td>
<td>{{school.name}}</td>
<td>{{school.street}}</td>
</tr>
</tbody>
</table>
server model
package model;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
#Entity
public class School {
#Id
#GeneratedValue
private int id;
private String name;
private String street;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getStreet() {
return street;
}
public void setStreet(String street) {
this.street = street;
}
}
resource
package rest;
import model.School;
import javax.inject.Inject;
import javax.transaction.Transactional;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import java.util.List;
#Path("school")
#Produces(MediaType.APPLICATION_JSON)
#Transactional
public class SchoolResource {
#Inject
SchoolDao dao;
#GET
public List<School> getAll() {
return dao.getAll();
}
#Path("id")
#GET
public School getById(#PathParam("id") int id) {
return dao.getById(id);
}
}
dao
package rest;
import model.School;
import javax.enterprise.context.Dependent;
import javax.inject.Inject;
import javax.persistence.EntityManager;
import java.util.List;
#Dependent
public class SchoolDao {
#Inject
EntityManager em;
public List<School> getAll() {
return em.createQuery("select s from School s", School.class).getResultList();
}
public School getById(int id) {
return em.find(School.class, id);
}
}
Thank you in advance, I think the problem must be on the server, because I tried showing data with a JSON file instead of Quarkus data already, and it does work.
As #R.Richards mentioned in a comment, putting "http://" in front of the url in the service file solved the problem.
I am trying to create 3 JPA repositories with 3 according services, but I don't even know how to start. Id appreciate if any of u takes a loot at this.
The book DTO
package com.mile.pc.java8.book_api_jpa.DTO;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name = "books")
public class Book {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private Long id;
private String name;
private String type;
private boolean available;
protected Book() {}
public Book(String name, String type, boolean available) {
super();
this.name = name;
this.type = type;
this.available = available;
}
public Long getID() {
return id;
}
public String getName() {
return name;
}
public String getType() {
return type;
}
public boolean isAvailable() {
return available;
}
#Override
public String toString() {
return "Book [id=" + id + ", name=" + name + ", type=" + type + ", available=" + available + "]";
}
}
the Order DTO:
package com.mile.pc.java8.book_api_jpa.DTO;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name = "orders")
public class Order {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private Integer id;
private String customerName;
protected Order() {}
public Order(Integer id, String customerName) {
super();
this.id = id;
this.customerName = customerName;
}
public int getId() {
return id;
}
public String getCustomerName() {
return customerName;
}
#Override
public String toString() {
return "Order [id=" + id + ", customerName=" + customerName + "]";
}
}
The client DTO:
package com.mile.pc.java8.book_api_jpa.DTO;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name = "clients")
public class Client {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private String clientEmail;
private String clientName;
protected Client() {}
public Client(String clientEmail, String clientName) {
super();
this.clientEmail = clientEmail;
this.clientName = clientName;
}
public String getClientEmail() {
return clientEmail;
}
public String getClientName() {
return clientName;
}
#Override
public String toString() {
return "Client [clientEmail=" + clientEmail + ", clientName=" + clientName + "]";
}
}
Book repo:
package com.mile.pc.java8.book_api_jpa.DTO.repo;
import java.util.ArrayList;
import java.util.List;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import com.mile.pc.java8.book_api_jpa.DTO.Book;
#EnableJpaRepositories
#Repository
public interface BookRepository extends CrudRepository<Book, Long> {
List<Book> books = new ArrayList<>();
}
Order repo:
package com.mile.pc.java8.book_api_jpa.DTO.repo;
import java.util.ArrayList;
import java.util.List;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import com.mile.pc.java8.book_api_jpa.DTO.Order;
#EnableJpaRepositories
#Repository
public interface OrderRepository extends CrudRepository<Order, Long> {
List<Order> orders = new ArrayList<Order>();
}
Client repo:
package com.mile.pc.java8.book_api_jpa.DTO.repo;
import java.util.HashMap;
import java.util.Map;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import com.mile.pc.java8.book_api_jpa.DTO.Client;
#EnableJpaRepositories
#Repository
public interface ClientRepository extends CrudRepository<Client, Long> {
Map<String, Client> clients = new HashMap<String, Client>();
}
Book Service:
package com.mile.pc.java8.book_api_jpa.DTO.repo.service;
import org.springframework.stereotype.Service;
#Service
public class BookService{
}
Order service:
package com.mile.pc.java8.book_api_jpa.DTO.repo.service;
import org.springframework.stereotype.Service;
#Service
public class OrderService {
}
Client Service:
package com.mile.pc.java8.book_api_jpa.DTO.repo.service;
import org.springframework.stereotype.Service;
#Service
public class ClientService {
}
I know It's a lot to ask. But I'd appreciate it a lot...Thank you :)
I am trying to add 2 values "name" and "city" to my 2 tables using #OneToOne. I think I write incomplete code at #Controller and wrong at Thymeleaf code. Help me . Thanks very much
Student.java
package com.example.demo.models;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;
import javax.persistence.Table;
#Entity
#Table(name = "student")
public class Student {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "student_id")
private long studentId;
#Column(name = "name")
private String name;
#OneToOne
#JoinColumn(name = "home_address_id")
private Address address;
public long getStudentId() {
return studentId;
}
public void setStudentId(long studentId) {
this.studentId = studentId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
}
Address.java
package com.example.demo.models;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name = "address")
public class Address {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "address_id")
private long addressId;
#Column(name = "city")
private String city;
public long getAddressId() {
return addressId;
}
public void setAddressId(long addressId) {
this.addressId = addressId;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
}
StudentRepository.java
package com.example.demo.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import com.example.demo.models.Student;
public interface StudentRepository extends JpaRepository<Student, Long> {
Student findByName (String name);
}
StudentService.java
package com.example.demo.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.example.demo.models.Student;
import com.example.demo.repository.StudentRepository;
#Service
public class StudentService {
#Autowired
private StudentRepository studentRepository;
public List<Student> findAll (){
return studentRepository.findAll();
}
public Student findByName (String name) {
return studentRepository.findByName(name);
}
public Student save (Student student) {
return studentRepository.save(student);
}
}
StudentController.Java
package com.example.demo.controller;
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 org.springframework.web.servlet.ModelAndView;
import com.example.demo.models.Student;
import com.example.demo.service.StudentService;
#Controller
public class StudentController {
#Autowired
private StudentService studentService;
#GetMapping("/all")
public ModelAndView getAll (ModelAndView modelAndView, Student student) {
modelAndView.addObject("student", studentService.findAll());
modelAndView.setViewName("all");
return modelAndView;
}
#GetMapping("/add")
public ModelAndView add (ModelAndView modelAndView, Student student) {
modelAndView.addObject("add", student);
modelAndView.setViewName("add");
return modelAndView;
}
#PostMapping("/add")
public ModelAndView postAdd (ModelAndView modelAndView, Student student) {
Student existStudent= studentService.findByName(student.getName());
if (existStudent!=null) {
modelAndView.setViewName("add");
}
else {
studentService.save(student);
modelAndView.setViewName("success");
}
return modelAndView;
}
}
add.html
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org">
<head>
<title>Add</title>
</head>
<body>
<center>
<form action="#" th:action="#{/add}" th:object="${add}" method="post">
<table>
<tr>
<td><label for="name">Name</label></td>
<td><input th:field="*{name}" type="text" name="name"></input></td>
</tr>
<tr>
<td><label for="city">City</label></td>
<td><input th:field="*{address.city}" type="text" name="address.city"></input>
</td>
</tr>
<tr>
<td><input type="submit" value="Submit"></input></td>
</tr>
</table>
</form>
</center>
</body>
</html>
student.sql
create table student (
student_id BIGINT NOT NULL AUTO_INCREMENT,
home_address_id BIGINT NOT NULL,
name VARCHAR(30) NOT NULL,
PRIMARY KEY (student_id),
CONSTRAINT student_address FOREIGN KEY (home_address_id) REFERENCES ADDRESS ( address_id)
);
Address.sql
create table ADDRESS (
address_id BIGINT NOT NULL AUTO_INCREMENT,
city VARCHAR(30) NOT NULL,
PRIMARY KEY (address_id)
);
I think I am wrong and may write incomplete. If possible, rewrite code snippets I need to fix or add. Thanks very much
I'm new to Spring and trying to build a sample application. In this I have a Company(OwnerCompany) which can have multiple locations(OwnerCompanyOffices). I am trying to save the company and it multiple locations at the same time using same JSP page.I'm not able to get proper data from my JSP page to the spring controller. My Hibernate logs are like this
OwnerCompanyOffices [id=0, name=null, location=null, ownerCompany=null]
Hibernate: insert into owner_company_offices (location, name, owner_company_id) values (?, ?, ?)
Here is my code
My OwnerCompany Entity OwnerCompany.java
package com.sachinmukherjee.spring_hibernate.entity;
import java.util.Set;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
#Entity
#Table(name = "owner_company")
public class OwnerCompany {
#Id
#Column(name = "id")
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
#Column(name="name")
private String name;
#Column(name = "short_name")
private String short_name;
#OneToMany(mappedBy = "owner_company",cascade = CascadeType.REMOVE,fetch = FetchType.LAZY)
private Set<Users> users;
#OneToMany(mappedBy = "ownerCompany", cascade = CascadeType.REMOVE, fetch = FetchType.EAGER)
private List<OwnerCompanyOffices> ownerCompanyOffices;
public OwnerCompany() {
super();
// TODO Auto-generated constructor stub
}
public OwnerCompany(String name, String short_name) {
this.name = name;
this.short_name = short_name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getShort_name() {
return short_name;
}
public void setShort_name(String short_name) {
this.short_name = short_name;
}
public Set<Users> getUsers() {
return users;
}
public void setUsers(Set<Users> users) {
this.users = users;
}
public List<OwnerCompanyOffices> getOwnerCompanyOffices() {
return ownerCompanyOffices;
}
public void setOwnerCompanyOffices(List<OwnerCompanyOffices> ownerCompanyOffices) {
this.ownerCompanyOffices = ownerCompanyOffices;
}
#Override
public String toString() {
return "OwnerCompany [id=" + id + ", name=" + name + ", short_name=" + short_name + ", users=" + users
+ ", ownerCompanyOffices=" + ownerCompanyOffices + "]";
}
public void addOwnerCompanyOffices(OwnerCompanyOffices ownerCompanyOffice) {
if(ownerCompanyOffices == null) {
ownerCompanyOffices = new ArrayList<OwnerCompanyOffices>();
}
ownerCompanyOffices.add(ownerCompanyOffice);
ownerCompanyOffice.setOwnerCompany(this);
}
}
My OwnerCompanyOffices Entity OwnerCompanyOffices.java
package com.sachinmukherjee.spring_hibernate.entity;
import javax.persistence.Column;
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.ManyToOne;
import javax.persistence.Table;
#Entity
#Table(name="owner_company_offices")
public class OwnerCompanyOffices {
#Id
#Column(name = "id")
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
#Column(name = "name")
private String name;
#Column(name="location")
private String location;
#ManyToOne(fetch = FetchType.EAGER)
#JoinColumn(name = "owner_company_id")
private OwnerCompany ownerCompany;
public OwnerCompanyOffices() {
super();
// TODO Auto-generated constructor stub
}
public OwnerCompanyOffices(String name, String location) {
this.name = name;
this.location = location;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public OwnerCompany getOwnerCompany() {
return ownerCompany;
}
public void setOwnerCompany(OwnerCompany ownerCompany) {
this.ownerCompany = ownerCompany;
}
#Override
public String toString() {
return "OwnerCompanyOffices [id=" + id + ", name=" + name + ", location=" + location + ", ownerCompany="
+ ownerCompany + "]";
}
}
My OwnerCompanyOfficesDAO class OwnerCompanyOfficesDAOImp
package com.sachinmukherjee.spring_hibernate.dao;
import java.util.List;
import javax.transaction.Transactional;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.sachinmukherjee.spring_hibernate.entity.OwnerCompanyOffices;
#Repository
public class OwnerCompanyOfficesDAOImp implements OwnerCompanyOfficesDAO {
#Autowired
SessionFactory sessionFactory;
public List<OwnerCompanyOffices> getAllOffices() {
// TODO Auto-generated method stub
return null;
}
#Transactional
public void saveOffice(OwnerCompanyOffices ownerCompanyOffice) {
Session session = sessionFactory.getCurrentSession();
session.saveOrUpdate(ownerCompanyOffice);
}
}
My OwnerCompanyController Class OwnerCompanyController
package com.sachinmukherjee.spring_hibernate.controller;
import java.util.List;
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.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.ui.Model;
import com.sachinmukherjee.spring_hibernate.dao.OwnerCompanyDAO;
import com.sachinmukherjee.spring_hibernate.dao.OwnerCompanyOfficesDAO;
import com.sachinmukherjee.spring_hibernate.entity.OwnerCompany;
import com.sachinmukherjee.spring_hibernate.entity.OwnerCompanyOffices;
#Controller
#RequestMapping("/owner_company/")
public class OwnerCompanyController {
#Autowired
private OwnerCompanyDAO ownerCompanyDAO;
#Autowired
private OwnerCompanyOfficesDAO ownerCompanyOfficesDAO;
#GetMapping("/add/")
public String add(Model model) {
OwnerCompanyOffices ownerCompanyOffices = new OwnerCompanyOffices();
model.addAttribute("ownerCompanyOffices", ownerCompanyOffices);
return "owner_company/add";
}
#PostMapping("/submit")
public String submit(#ModelAttribute("ownerCompanyOffices") OwnerCompanyOffices ownerCompanyOffices) {
System.out.println(ownerCompanyOffices);
ownerCompanyOfficesDAO.saveOffice(ownerCompanyOffices);
return "redirect:/owner_company/";
}
}
My add.jsp page where I'm entering the ownercompany and ownercompanyoffices data
<div class="row">
<div class="col-md-12">
<form action="${pageContext.request.contextPath}/owner_company/submit/" method="POST" modelAttribute="ownerCompanyOffices" class="form-control">
<label>Name</label>
<input name="ownerCompanyOffices.ownerCompany.name" required="required"/>
</br></br>
<label>Short Name</label>
<input name="ownerCompanyOffices.ownerCompany.short_name" type="text" />
</br></br>
<table class="table table-responsive">
<thead>
<tr>
<th>Name</th>
<th>Location</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<tr class="toClone">
<td><input type="text" name="ownerCompanyOffices.name" required="required"/></td>
<td><input type="text" name="ownerCompanyOffices.location" required="required"/></td>
<td class="remove"></td>
</tr>
<tr id="addRow">
<td></td>
<td></td>
<td>Add More
</tr>
</tbody>
</table>
<button type="submit" class="btn btn-success">Save</button>
</form>
</div>
</div>
</body>
</html>
<script type="text/javascript">
$(document).on("click",".addMore", function(){
var clonedRow = $(".toClone:first").clone();
$(clonedRow).find("input").each(function(){
$(this).val("");
});
$(clonedRow).addClass("toRemove");
$(clonedRow).find(".remove").addClass("removeRow");
$(clonedRow).find(".remove").html("<a href='#'>Remove</a>");
$(clonedRow).insertBefore($("#addRow"));
});
$(document).on("click",".removeRow", function(){
$(this).closest("tr").remove();
});
</script>
Here By clicking on add more link user can add multiple offices against a single company.
I'm building a project with spring boots, checking the status of the Internet through control, and I'm in the process of a DB connection.
I'm trying to do 'MyBatis', but there's an error.
This is a list of my directories:
MinitoringdataApplication.java
package com.smartcore.mn.springboot;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
#MapperScan(basePackages = "com.smartcore.mn.springboot")
public class MinitoringdataApplication {
public static void main(String[] args) {
SpringApplication.run(MinitoringdataApplication.class, args);
}
}
ServletInitializer.java
package com.smartcore.mn.springboot;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
public class ServletInitializer extends SpringBootServletInitializer {
#Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(MinitoringdataApplication.class);
}
}
ApiController.java
package com.smartcore.mn.springboot.controller;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import com.smartcore.mn.springboot.model.Member;
import com.smartcore.mn.springboot.service.MemberService;
#RestController
public class ApiController {
#Autowired
MemberService memberService;
#GetMapping(path = "/helloWorld")
public String helloWorld() {
return LocalDateTime.now().format(DateTimeFormatter.ISO_LOCAL_DATE_TIME);
}
#GetMapping(path = "/db")
public List<Member> selectAllMember() {
List<Member> members = memberService.getAllMember();
return members;
}
}
MemberMapper.interface
package com.smartcore.mn.springboot.mapper;
import java.util.List;
import org.apache.ibatis.annotations.Mapper;
import com.smartcore.mn.springboot.model.Member;
#Mapper
public interface MemberMapper {
Member selectMemberById(Long id);
List<Member> selectAllMember();
void insertMember(Member member);
}
Member.java
package com.smartcore.mn.springboot.model;
import java.util.Date;
import org.apache.ibatis.type.Alias;
import com.smartcore.mn.springboot.Exception.IdPasswordNotMatchingException;
import lombok.Data;
#Data
#Alias("member")
public class Member {
private Long id;
private String email;
private String password;
private String name;
private Date registerDate;
public Member(String email, String password, String name, Date registerDate) {
this.email = email;
this.password = password;
this.name = name;
this.registerDate = registerDate;
}
public void setId(Long id) {
this.id = id;
}
public Long getId() {
return id;
}
public String getEmail() {
return email;
}
public String getPassword() {
return password;
}
public String getName() {
return name;
}
public Date getRegisterDate() {
return registerDate;
}
public void changePassword(String oldPassword, String newPassword) {
if (!password.equals(oldPassword))
throw new IdPasswordNotMatchingException();
this.password = newPassword;
}
}
MemberService.java
package com.smartcore.mn.springboot.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.smartcore.mn.springboot.mapper.MemberMapper;
import com.smartcore.mn.springboot.model.Member;
#Service
#Transactional
public class MemberService {
#Autowired
MemberMapper memberMapper;
public Member getMemberById(Long id) {
return memberMapper.selectMemberById(id);
}
public List<Member> getAllMember() {
return memberMapper.selectAllMember();
}
public void addMember(Member member) {
memberMapper.insertMember(member);
}
}
application.properties
spring.datasource.url=jdbc:mysql://localhost/mydb?serverTimezone=UTC&autoReconnection=true
spring.datasource.username=mydb
spring.datasource.password=mydb
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
mybatis.type-aliases-package=com.smartcore.mn.springboot.model
logging.level.com.smartcore.mn.springboot.mapper=TRACE
MemberMapper.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.smartcore.mn.springboot.mapper.MemberMapper">
<select id="selectMemberById" resultType="member">
SELECT *
FROM MEMBER
WHERE ID = #{id}
</select>
<select id="selectAllMember" resultType="member">
SELECT *
FROM MEMBER
</select>
<insert id="insertMember">
INSERT INTO MEMBER (EMAIL, PASSWORD, NAME, REGDATE)
VALUES (#{email}, #{password}, #{name}, #{registerDate})
</insert>
</mapper>
http://localhost:8080/helloworld is works normally.
But http://localhost:8080/db have see Error
I need your solution. Thank you in advance.
my TABLE
As mentioned in our discussion in comments, MyBatis is trying to map your NAME column in result-set to the registerDate argument in the Member constructor.
Since you did not specify paramName for each fields, the order of arg elements in the constructor is error-prone.
Try mapping your result-set to your constructor with correct ordered args:
Member(String email, String password, String name, Date registerDate) should match SELECT EMAIL, PASSWORD, NAME, REGDATE FROM MEMBER
or
Member(Long id, String email, String password, String name, Date registerDate) should match SELECT * FROM MEMBER