Getting data from database - mysql

I'm trying to retrieve data from database in Primefaces datatable. My database table name is dept and it has two columns id (int not null primary key) and name (varchar 255 not null). I'm using println to show size of records. But after starting project nothing show up. In database table are 2 records.
DeptTest.java
package logon;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.enterprise.context.SessionScoped;
import javax.faces.bean.ViewScoped;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceUnit;
import javax.persistence.Query;
#ViewScoped
#SessionScoped
#javax.faces.bean.ManagedBean(name = "depTest")
public class DeptTest implements Serializable {
private static final long serialVersionUID = 1L;
private static final ArrayList<Department> orderList = new ArrayList<Department>();
public ArrayList<Department> getOrderList() {
return orderList;
}
#PersistenceUnit(unitName = "Webbeans_RESOURCE_LOCAL")
private EntityManagerFactory emf;
public List<Department> getDeptList() {
return deptList;
}
public void setDeptList(List<Department> deptList) {
this.deptList = deptList;
}
public List<Department> deptList = new ArrayList();
#PostConstruct
public void init() {
EntityManager em = emf.createEntityManager();
// Read the existing entries and write to console
Query q = em.createQuery("SELECT d FROM Dept d");
deptList = q.getResultList();
System.out.println("Size dept: " + deptList.size());
}
}

Related

Need to get Spring to return MySQL View data back to REACT front end

I am trying to get my Spring MySQL backend to return a mutli table VIEW (not a single table) thru AXIOS to my REACT front end.
I am testing my Backend with POSTMAN (http://localhost:8080/api/v1/cpysiteassetview)
I get an error messages from SPRING and a long error message from POSTMAN (below).
I am close, but going wrong somewhere and I hope someone more familiar with this can shed some light and explain where I am going wrong.
Here is the VIEW\MODEL\REPOSITORY\CONTROLLER.
...
CREATE
ALGORITHM = UNDEFINED
DEFINER = `root`#`localhost`
SQL SECURITY DEFINER
VIEW `cpysiteasset` AS
SELECT
`cpymaster`.`cpymasterid` AS `cpymasterid`,
`cpymaster`.`cpymastercode` AS `cpymastercode`,
`cpymaster`.`cpymastername` AS `cpymastername`,
`sitemaster`.`sitemasterid` AS `sitemasterid`,
`sitemaster`.`sitemastercode` AS `sitemastercode`,
`sitemaster`.`sitemastername` AS `sitemastername`,
`assets`.`assetsid` AS `assetsid`,
`assets`.`assetsidentifier` AS `assetsidentifier`,
`assets`.`assetsname` AS `assetsname`
FROM
((`cpymaster`
JOIN `sitemaster` ON = `cpymaster`.`cpymasterid`)))
JOIN `assets` ON ((`assets`.`sitemaster_sitemasterid` = `sitemaster`.`sitemasterid`)))
ORDER BY `sitemaster`.`sitemastercode` , `assets`.`assetsidentifier`
//MODEL
package net.javaguides.springboot.model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import org.hibernate.annotations.Immutable;
#Entity
#Immutable
#Table(name = "`cpysiteassetview`")
public class CpySiteAssetView {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
private int cpymasterid;
private String cpymastercode;
private String cpymastername;
private int sitemasterid;
private String sitemastercode;
private String sitemastername;
private int assetsid;
private String assetsidentifier;
private String assetsname;
#Column(name = "cpymasterid")
public int getCpymasterid() {
return cpymasterid;
}
#Column(name = "cpymastercode")
public String getCpymastercode() {
return cpymastercode;
}
#Column(name = "cpymastername")
public String getCpymastername() {
return cpymastername;
}
#Column(name = "sitemasterid")
public int getSitemasterid() {
return sitemasterid;
}
#Column(name = "sitemastercode")
public String getSitemastercode() {
return sitemastercode;
}
#Column(name = "sitemastername")
public String getSitemastername() {
return sitemastername;
}
#Column(name = "assetsid")
public int getAssetsid() {
return assetsid;
}
#Column(name = "assetsidentifier")
public String getAssetsidentifier() {
return assetsidentifier;
}
#Column(name = "assetsname")
public String getAssetsname() {
return assetsname;
}
}
//Repository
package net.javaguides.springboot.repository;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import net.javaguides.springboot.model.CpySiteAssetView;
#Repository
public interface CpySiteAssetViewRepository1 extends JpaRepository<CpySiteAssetView, Long>{
public List<CpySiteAssetView> findAll();
}
//Controller
package net.javaguides.springboot.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import net.javaguides.springboot.model.CpySiteAssetView;
import net.javaguides.springboot.repository.CpySiteAssetViewRepository1;
#CrossOrigin(origins = "http://localhost:3000")
#RestController
#RequestMapping("/api/v1/")
public class CpySiteAssetViewController {
#Autowired
private CpySiteAssetViewRepository1 cpySiteAssetViewRepository1;
//get all
#GetMapping("/cpysiteassetview")
public List<CpySiteAssetView> getAllCpySiteAssetView(){
return cpySiteAssetViewRepository1.findAll();
}
}
...
Error Message from Spring:
java.sql.SQLSyntaxErrorException: Unknown column 'cpysiteass0_.id' in 'field list'
Error Message from Postman (first part):
"error": "Internal Server Error",
"trace": "org.springframework.dao.InvalidDataAccessResourceUsageException: could not extract ResultSet; SQL [n/a]; nested exception is org.hibernate.exception.SQLGrammarException: could not extract ResultSet\r\n\tat org.springframework.orm.jpa.vendor.HibernateJpaDialect.convertHibernateAccessException(HibernateJpaDialect.java:259)\r\n\tat org.springframework.orm.jpa.vendor.HibernateJpaDialect.translateExceptionIfPossible(HibernateJpaDialect.java:233)\r\n\tat org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.translateExceptionIfPossible(AbstractEntityManagerFactoryBean.java:551)\r\n\tat org.springframework.dao.support.ChainedPersistenceExceptionTranslator.translateExceptionIfPossible(ChainedPersistenceExceptionTranslator.java:61)\r\n\tat org.springframework.dao.support.DataAccessUtils.translateIfNecessary(DataAccessUtils.java:242)\r\n\tat org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(Per
OK..commented out //private long id;
and now it works !!!!!

Spring - can't save an entity with CRUD Repository

I am making simple program that have to get some info from OpenWeatherMap API and save it in MySQL database:
package com.example.restTemplate;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;
#SpringBootApplication
public class RestTemplateApplication {
public static void main(String[] args) {
SpringApplication.run(RestTemplateApplication.class, args);
}
#Bean
public RestTemplate getRestTemplate() {
return new RestTemplate();
}
}
package com.example.restTemplate.Model;
import lombok.*;
import javax.persistence.Entity;
import javax.persistence.Id;
#NoArgsConstructor
#AllArgsConstructor
#Entity
#javax.persistence.Table(name="Weather")
#Getter
#Setter
#ToString
public class WeatherScore {
#Id
private int id;
private String city;
private double temperature;
private int pressure;
private long currentDate;
}
package com.example.restTemplate.Controller;
import com.example.restTemplate.Model.WeatherScore;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
#Repository
public interface WeatherCRUDRepository
extends CrudRepository<WeatherScore, Long> {
WeatherScore save (WeatherScore score);
}
package com.example.restTemplate.Controller;
import com.example.restTemplate.Model.WeatherScore;
import org.springframework.context.ApplicationContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import java.util.Arrays;
import java.util.Random;
#RestController
public class ConsumeWebService {
#Autowired
RestTemplate restTemplate;
WeatherCRUDRepository repository;
ApplicationContext context;
#RequestMapping(value = "/weather")
public void printWeather() {
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
HttpEntity<String> entity = new HttpEntity<String>(headers);
String text = restTemplate.exchange("http://api.openweathermap.org/data/2.5/weather?q=London,uk&APPID=mykey",
HttpMethod.GET, entity, String.class).getBody();
int pressureStartIndex = text.indexOf("pressure")+10;
int pressureEndIndex = text.indexOf(",", pressureStartIndex);
int tempStartIndex = text.indexOf("temp")+6;
int tempEndIndex = text.indexOf(",", tempStartIndex);
int pressure = Integer.parseInt(text.substring(pressureStartIndex, pressureEndIndex));
double temperature = Double.parseDouble(text.substring(tempStartIndex, tempEndIndex));
WeatherScore score = new WeatherScore();
score.setCity("London");
score.setPressure(pressure);
score.setTemperature(temperature);
Random generator = new Random();
score.setId(generator.nextInt(1000));
score.setCurrentDate(System.currentTimeMillis());
WeatherCRUDRepository repo = context.getBean(WeatherCRUDRepository.class);
repository.save(score);
}
}
When i tap http://localhost:8080/weather i get an error:
Cannot invoke
"org.springframework.context.ApplicationContext.getBean(java.lang.Class)"
because "this.context" is null
Blockquote
How i could fix that?
You have to autowire all the beans within controller, like so:
#Autowired
RestTemplate restTemplate;
#Autowired
WeatherCRUDRepository repository;
#Autowired
ApplicationContext context;

Upload excel file content to mysql using Spring boot and UI

I'm trying to upload excel file content to mysql using Spring boot with the help of upload file UI. Need help with that.
But i'm facing Whitelabel Error Page. I've tried couple of things but no luck yet.
Project View
ReadFileApplication.java
package com.springboot.file.parsefiles;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
#Configuration
#EnableAutoConfiguration
#ComponentScan(basePackages= {"com.springboot.file.parsefiles.controller"})
#SpringBootApplication
#Component
public class ReadFileApplication {
public static void main(String[] args) {
SpringApplication.run(ReadFileApplication.class, args);
}
}
ReadFileConrtroller.java
package com.springboot.file.parsefiles.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import com.springboot.file.parsefiles.service.ReadFileService;
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.RestController;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import com.springboot.file.parsefiles.model.User;
#RestController
public class ReadFileController
{
#Autowired private ReadFileService readFileService;
#GetMapping(value="/ ")
public String home(Model model)
{
model.addAttribute("user", new User());
List<User> users = ReadFileService.findAll();
model.addAttribute("users", users);
return "view/users";
}
#PostMapping(value="/fileupload")
public String uploadFile(#ModelAttribute User user, RedirectAttributes redirectAttributes)
{
#SuppressWarnings("unused")
boolean isFlag = readFileService.saveDataFromUploadFile(user.getFile());
return "redirect:/";
}
}
ReadFileRepository.java
package com.springboot.file.parsefiles.repository;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import com.springboot.file.parsefiles.model.User;
#Repository
public interface ReadFileRepository extends CrudRepository<User, Long>
{
}
ReadFileService.java
package com.springboot.file.parsefiles.service;
import java.util.List;
import org.springframework.web.multipart.MultipartFile;
import com.springboot.file.parsefiles.model.User;
public interface ReadFileService
{
List<User> findAll = null;
static List<User> findAll()
{
return null;
}
boolean saveDataFromUploadFile(MultipartFile file);
}
ReadFileServiceImpl.java
package com.springboot.file.parsefiles.service;
import java.util.List;
import com.springboot.file.parsefiles.service.ReadFileService;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import com.springboot.file.parsefiles.model.User;
import com.springboot.file.parsefiles.repository.ReadFileRepository;
#Service
#Transactional
public class ReadFileServiceImpl implements ReadFileService
{
#Autowired private ReadFileRepository readFileRepository;
public List<User> findAll()
{
return (List<User>) readFileRepository.findAll();
}
#Override
public boolean saveDataFromUploadFile(MultipartFile file) {
#SuppressWarnings("unused")
boolean isFlag = false;
String extension = FilenameUtils.getExtension(file.getOriginalFilename());
if(extension.equalsIgnoreCase("json"))
{
isFlag = realDataFromJson(file);
}else if(extension.equalsIgnoreCase("csv"))
{
isFlag = realDataFromCsv(file);
}
return false;
}
private boolean realDataFromCsv(MultipartFile file)
{
return false;
}
private boolean realDataFromJson(MultipartFile file)
{
return false;
}
}
Applicatiopn.properties
spring.datasource.url = jdbc:mysql://localhost:3306/sampledatabase
spring.datasource.username = root
spring.datasource.password = root
spring.datasource.testWhileIdle = true
spring.datasource.validationQuery = SELECT 1
spring.jpa.show-sql = true
spring.jpa.hibernate.ddl-auto = update
spring.jpa.hibernate.naming-strategy = org.hibernate.cfg.ImprovedNamingStrategy
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect
spring.servlet.multipart.max-file-size=100MB
spring.servlet.multipart.max-request-size=500MB
Edit:
***************************
APPLICATION FAILED TO START
***************************
Description:
Field readFileService in com.springboot.file.parsefiles.controller.ReadFileController required a bean of type 'com.springboot.file.parsefiles.service.ReadFileService' that could not be found.
The injection point has the following annotations:
- #org.springframework.beans.factory.annotation.Autowired(required=true)
Action:
Consider defining a bean of type 'com.springboot.file.parsefiles.service.ReadFileService' in your configuration.
Update your controller as below
#PostMapping(value="/fileupload")
public String uploadFile(#RequestParam MultipartFile file, RedirectAttributes redirectAttributes)
{
#SuppressWarnings("unused")
boolean isFlag = readFileService.saveDataFromUploadFile(file);
return "redirect:/";
}
Next i used apache-poi library to convert excel file to list of model object in service class. So my service method is as below
#Autowired
private IPoiji poijiImpl;
#Override
public boolean saveDataFromUploadFile(MultipartFile file) {
List<UserDTO> uploadedUserList = = poijiImpl.fromExcel(file.getOriginalFilename(), file.getInputStream(),UserDTO.class);
// here i can call repository methods to save data in database
}

Spring Boot Hibernate ManyToMany Relation using embedded model

I have a question about ManyToMany realation. Let's assume we have two model domains like Menu and RoleGroup,my Menu model includes a field named ' private RoleGroup roleGroup ' with #ManyToMany relation and #JoinTable with JoinColumns and InverseJoinColumns.
Imagine I already created an object like Menu that includes RoleGroup field with entityRepository .save in my database Here is my question, is there any way to update my object (considering to ManyToMany relation) without using native query? because when we use ManyToMany relationship hibernate handles it by creating third table like "Menu_RoleGroup" in database where as we don't have a domain like Menu_RoleGroup .
//Here is my application
package org.sayar.layout.domain;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import org.hibernate.annotations.Nationalized;
import org.sayar.layout.base.general.domain.GeneralDomain;
import org.sayar.layout.constants.SchemaList;
import org.sayar.layout.domain.uaa.Role;
import org.sayar.layout.domain.uaa.RoleGroup;
import org.springframework.data.annotation.Transient;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonManagedReference;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
/**
* This domain for store and transfer Menu
*
* #author Ehsan
*/
#Setter
#Getter
#AllArgsConstructor
#NoArgsConstructor
#JsonInclude(JsonInclude.Include.NON_NULL)
#Entity(name = Menu.TABLE_NAME)
#Table(name = Menu.TABLE_NAME, schema = SchemaList.LAYOUT)
public class Menu extends GeneralDomain {
#Transient
public final static String TABLE_NAME = "Menu";
public class CN {
public final static String title = "title";
public final static String description = "description";
public final static String banner = "banner";
}
#Nationalized
#Column(name = CN.title, length = 128, nullable = false)
private String title;
#Nationalized
#Column(name = CN.description, length = 1000)
private String description;
#Nationalized
#Column(name = CN.banner, length = 128)
private String banner;
/* Relationships */
#ManyToMany(fetch = FetchType.EAGER)
#JoinTable(name = "Menu_RoleGroup",
schema = SchemaList.LAYOUT,
joinColumns = #JoinColumn(name = "menuId", referencedColumnName = GCN.id), //
inverseJoinColumns = #JoinColumn(name = "roleGroupId", referencedColumnName = GCN.id))
private Set<RoleGroup> roleGroupSet;
#OneToMany(mappedBy = MenuItem.CN.menu, fetch = FetchType.EAGER)
#JsonManagedReference
private Set<MenuItem> menuItemSet = new HashSet<>();
/* Constructors */
public Menu(String title, String banner, String description) {
this.title = title;
this.banner = banner;
this.description = description;
}
public Menu(String title, String banner, String description, Set<RoleGroup> roleGroupSet) {
this.title = title;
this.banner = banner;
this.description = description;
this.roleGroupSet = roleGroupSet;
}
public Menu(String id) {
super(id);
}
/* Other classes or enumerations */
}
.
.
.
.
.
package org.sayar.layout.domain.uaa;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.Table;
import org.hibernate.annotations.Nationalized;
import org.sayar.layout.base.general.domain.GeneralDomain;
import org.sayar.layout.constants.SchemaList;
import org.springframework.data.annotation.Transient;
import com.fasterxml.jackson.annotation.JsonInclude;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
/**
* This domain for store and transfer RoleGroup
*
* #author Ehsan
*
*/
#Setter
#Getter
#AllArgsConstructor
#NoArgsConstructor
#JsonInclude(JsonInclude.Include.NON_NULL)
#Entity(name = RoleGroup.TABLE_NAME)
#Table(name = RoleGroup.TABLE_NAME, schema = SchemaList.UAA)
public class RoleGroup extends GeneralDomain {
#Transient
public final static String TABLE_NAME = "RoleGroup";
public class CN {
public final static String title = "title";
public final static String status = "status";
}
#Nationalized
#Column(name = CN.title, length = 128, nullable = false)
private String title;
#Enumerated(EnumType.STRING)
#Column(name = CN.status, nullable = false)
private Status status;
public RoleGroup(String id) {
super(id);
}
/* Relationships */
/* Constructors */
/* Other classes or enumerations */
public enum Status {
ACTIVE, DE_ACTIVE
}
}
.
.
.
package org.sayar.layout.service.menu;
import org.sayar.layout.base.util.Print;
import org.sayar.layout.domain.Menu;
import org.sayar.layout.repository.megaitem.MegaItemRepository;
import org.sayar.layout.repository.menu.MenuRepository;
import org.sayar.layout.repository.menuitem.MenuItemRepository;
import org.sayar.layout.rest.menu.dto.*;
import org.springframework.stereotype.Service;
import org.sayar.layout.dao.menu.MenuDaoImpl;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.http.ResponseEntity;
import java.util.List;
import lombok.RequiredArgsConstructor;
import org.springframework.transaction.annotation.Transactional;
import reactor.core.publisher.Mono;
/**
* Spring service implementation for the Menu entity.
*
* #author Ehsan
*/
#Service
#RequiredArgsConstructor
public class MenuServiceImpl implements MenuService {
private final MenuDaoImpl entityDao;
private final MenuRepository entityRepository;
private final MenuItemRepository menuItemRepository;
private final MegaItemRepository megaItemRepository;
#Override
public Mono<ResponseEntity<Boolean>> create(ReqMenuCreateDTO entity, String userId) {
return Mono.just(entityRepository.save(entity.map(userId)))
.flatMap(createdEntity -> Mono.just(ResponseEntity.ok().body(true))
)
.defaultIfEmpty(ResponseEntity.ok().body(false));
}
#Transactional
#Override
public Mono<ResponseEntity<Boolean>> update(String id, ReqMenuUpdateDTO entity) {
Mono.just(entityRepository.update(id, entity.getTitle(), entity.getBanner(), entity.getDescription())).subscribe();
Mono.just(entityRepository.deleteRoleMenu(id)).subscribe();
Print.print("title", entity);
if (entity.getRoleGroupIdSet() != null && !entity.getRoleGroupIdSet().isEmpty())
for (String roleId : entity.getRoleGroupIdSet()) {
Mono.just(entityRepository.updateRoleMenu(id, roleId)).subscribe();
}
return Mono.just(ResponseEntity.ok().body(true));
}
.
.
.
.
.
package org.sayar.layout.repository.menu;
import org.sayar.layout.constants.SchemaList;
import org.sayar.layout.repository.menu.dto.ResRoleGetListRepoDTO;
import org.sayar.layout.rest.menu.dto.ResMenuGetListDTO;
import org.sayar.layout.repository.menu.dto.ResMenuGetOneRepoDTO;
import org.sayar.layout.rest.menu.dto.ResMenuGetOneDTO;
import org.sayar.layout.rest.menu.dto.ResMenuGetPageDTO;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import java.util.List;
import java.util.Optional;
import org.sayar.layout.domain.Menu;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.transaction.annotation.Transactional;
/**
* Spring Data SQL Server repository for the Menu entity.
*
* #author Ehsan
*/
#Repository
public interface MenuRepository extends JpaRepository<Menu, String> {
// UPDATE ALL STARTS HERE
#Transactional
#Modifying
#Query(value = "UPDATE Menu AS m SET m.title = :title , m.description = :description, m.banner = :banner WHERE m.id = :id")
Integer update(#Param("id") String id, #Param("title") String title, #Param("description") String description, #Param("banner") String banner);
#Transactional
#Modifying
#Query(value = "DELETE FROM layout.Menu_RoleGroup WHERE menuId = :id", nativeQuery = true)
Integer deleteRoleMenu(#Param("id") String id);
#Transactional
#Modifying
#Query(value = "INSERT INTO layout.Menu_RoleGroup (menuId,roleGroupId) VALUES (:menuId,:roleGroupId)", nativeQuery = true)
Integer updateRoleMenu(#Param("menuId") String menuId, #Param("roleGroupId") String roleGroupId);
}
Actually I find out how to solve it!
In this case I have to create a domain model like MenuRoleGroup as an Entity and then add an Embeddable field e.g MenuRoleGroupEmbeddable and use create #EmbeddedId field within MenuRoleGroup.
then add the primary key of Menu and RoleGroup within MenuRoleGroupEmbeddable.
so Spring Data is able to create MenuRoleGroupRepository that extends JPA Repository and but notice that this table has two primary keys not one.
notice that MenuRoleGroupEmbeddable field within MenuRoleGroup doesn't has relationship but Menu and RoleGroup both have #ManyToOne relation with MenuRoleGroupEmbeddable model.
here is the example.
package org.sayar.wms.domain.Menu;
import com.fasterxml.jackson.annotation.JsonInclude;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import org.hibernate.annotations.GenericGenerator;
import org.sayar.wms.base.general.domain.GeneralDomain;
import org.sayar.wms.constants.SchemaList;
import org.sayar.wms.domain.container.Container;
import org.sayar.wms.domain.product.ProductContainerEmbeddable;
import org.springframework.data.annotation.Transient;
import javax.persistence.*;
import java.util.Date;
#Setter
#Getter
#AllArgsConstructor
#NoArgsConstructor
#JsonInclude(JsonInclude.Include.NON_NULL)
#Entity(name = MenuRoleGroup.TABLE_NAME)
#Table(name = MenuRoleGroup.TABLE_NAME, schema = SchemaList.WMS)
public class MenuRoleGroup {
#Transient
public final static String TABLE_NAME = "MenuRoleGroup";
public class CN {
public final static String startDate = "startDate";
}
#EmbeddedId
private MenuRoleGroupEmbeddable menuRoleGroupEmbeddable;
#JoinColumn(name = CN.startDate, referencedColumnName = GeneralDomain.GCN.id)
private Date startDate;
}
package org.sayar.wms.domain.Menu;
import com.fasterxml.jackson.annotation.JsonInclude;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import org.sayar.wms.base.general.domain.GeneralDomain;
import org.sayar.wms.domain.container.Container;
import javax.persistence.CascadeType;
import javax.persistence.Embeddable;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import java.io.Serializable;
import java.util.Set;
/**
* This domain for store and transfer Warehouse
*
* #author masoud
*/
#Setter
#Getter
#AllArgsConstructor
#NoArgsConstructor
#JsonInclude(JsonInclude.Include.NON_NULL)
#Embeddable
public class ProductContainerEmbeddable implements Serializable {
public class CN {
public final static String menuId = "menuId";
public final static String roleGroupId = "roleGroupId";
}
/* Relationships */
#ManyToOne
#JoinColumn(name = CN.menu, referencedColumnName = "id")
private Menu menu;
#ManyToOne
#JoinColumn(name = CN.roleGroup, referencedColumnName ="id")
private RoleGroup roleGroup;
/* Constructors */
/* Other classes or enumerations */
}
menuId and roleGroupId are both primary keys of hte MenuRoleGroup entity.

My tableview is displaying blank rows [duplicate]

This question already has answers here:
Javafx tableview not showing data in all columns
(3 answers)
Closed 7 years ago.
I am new to JavaFX and I have been trying to implement this code for displaying data from MySQL database in a TableView. The problem is that when I run the code I get blank rows and I don't know why.
Here is my code for the class:
import java.io.IOException;
import java.net.URL;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.ResourceBundle;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Node;
import javafx.scene.control.Alert;
import javafx.scene.control.Button;
import javafx.scene.control.ButtonType;
import javafx.scene.control.ComboBox;
import javafx.scene.control.DatePicker;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.layout.AnchorPane;
import javafx.stage.Stage;
import javax.swing.JOptionPane;
public class FXMLPatientsMasterController implements Initializable {
/*
mysql connection variables
*/
Connection conn=null;
PreparedStatement pat=null;
ResultSet rs=null;
private ObservableList<PatientDetails> patients;
#FXML
private TableView Table_Patients;
#FXML
private TableColumn patientID;
#FXML
private TableColumn Name;
#FXML
private TableColumn Surname;
#FXML
private TableColumn pnationalID;
#FXML
private TableColumn psex;
#FXML
private TableColumn pDOB;
// Some code here
#Override
public void initialize(URL url, ResourceBundle rb) {
// TODO
conn = PMS263MySqlConnection.ConnectDB();
try {
patients = FXCollections.observableArrayList();
rs = conn.createStatement().executeQuery("select * from patients");
while (rs.next()) {
patients.add(new PatientDetails(rs.getInt("PatientId"),
rs.getString("fName"), rs.getString("Surname"), rs.getString("National_ID"), rs.getString("Sex"), rs.getString("DOB")));
}
patientID.setCellValueFactory(new PropertyValueFactory("PatientId"));
Name.setCellValueFactory(new PropertyValueFactory("fName"));
Surname.setCellValueFactory(new PropertyValueFactory("Surname"));
pnationalID.setCellValueFactory(new PropertyValueFactory("National_ID"));
psex.setCellValueFactory(new PropertyValueFactory("Sex"));
pDOB.setCellValueFactory(new PropertyValueFactory("DOB"));
Table_Patients.setItems(null);
Table_Patients.setItems(patients);
} catch (Exception e) {
e.printStackTrace();
System.out.println("Error on Building Data");
}
}
public static class PatientDetails {
private final SimpleIntegerProperty Patientid;
private final StringProperty Pname;
private final StringProperty Psurname;
private final StringProperty Pnationalid;
private final StringProperty Psex;
private final StringProperty Pdob;
private PatientDetails(int patientid, String pname, String psurname, String pnationalid, String psex, String pdob) {
this.Patientid = new SimpleIntegerProperty(patientid);
this.Pname = new SimpleStringProperty(pname);
this.Psurname = new SimpleStringProperty(psurname);
this.Pnationalid = new SimpleStringProperty(pnationalid);
this.Psex= new SimpleStringProperty(psex);
this.Pdob = new SimpleStringProperty(pdob);
}
public SimpleIntegerProperty patientidProperty() {
return Patientid ;
}
public StringProperty pnameProperty() {
return Pname;
}
public StringProperty psurnameProperty() {
return Psurname;
}
public StringProperty pnationalidProperty() {
return Pnationalid;
}
public StringProperty psexPsexProperty() {
return Psex;
}
public StringProperty pdobProperty() {
return Pdob;
}
}
}
Assuming your database query works, you the property names wrong:
If the property "getter" is named myNameProperty() you need to use new PropertyValueFactory("myName").
Either the property "getters" need to be renamed or the strings used with the value factories:
patientID.setCellValueFactory(new PropertyValueFactory("patientId"));
Name.setCellValueFactory(new PropertyValueFactory("pname"));
Surname.setCellValueFactory(new PropertyValueFactory("psurname"));
pnationalID.setCellValueFactory(new PropertyValueFactory("pnationalid"));
psex.setCellValueFactory(new PropertyValueFactory("psex"));
pDOB.setCellValueFactory(new PropertyValueFactory("pdob"));
...
public SimpleIntegerProperty patientIdProperty() {
return Patientid;
}
public StringProperty pnameProperty() {
return Pname;
}
public StringProperty psurnameProperty() {
return Psurname;
}
public StringProperty pnationalidProperty() {
return Pnationalid;
}
public StringProperty psexProperty() {
return Psex;
}
public StringProperty pdobProperty() {
return Pdob;
}