jparepository does not stock blob properly - mysql

i could'n stock byte in mysql database table using "jpa" hibernate under spring "mvc"
am getting file as multipart :file and some text from form
tables are created dynamically with hibernate
when trying to save file with form data,the data is stocked properly ,but about the file just 4 bytes blob stocked
the entity is like
import java.util.Set;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Lob;
import javax.persistence.OneToMany;
import javax.persistence.Table;
#Entity
#Table(name = "store")
public class Store {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name="storeid", updatable = false, nullable = false)
#org.springframework.data.annotation.Id
private Long storeid;
#Column(name = "stor_Name")
private String storName;
...
#Column(name = "stor_Logo", columnDefinition="BLOB")
#Lob
private byte[] storLogo;
#Column(name = "stor_Email")
private String storEmail;
#Column(name = "stor_Phone")
private String storPhone;
#OneToMany(mappedBy = "store")
private Set<Product> storProducts;
public Store(Long storeid,
String storName,
String storDesc,
byte[] storLogo,
Double storPrice,
String storeEmail,
String storePhone,
Set<Product> storProducts
) {
this.storeid = storeid;
this.storName = storName;
this.storDesc = storDesc;
this.storLogo = storLogo;
this.storEmail = storeEmail;
this.storPhone = storePhone;
this.storProducts = storProducts;
}
... setters and getters
repository is coded as well
import com.openstore.models.Store;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
#Repository
public interface StoreRepository extends JpaRepository<Store, Long> {
Store findByStorName(final String storName);
}
all is stocking properly except "storLogo" it stocks just 4 bytes of blob
i tray to change in application.proprieties to verify if the problem is "http" problem by modifying accepted file size , so it does not accept over sizing files
so i debug repository controller :
#RequestMapping(value = "save", method = RequestMethod.POST, consumes =
"multipart/form-data")
public String save(#RequestParam String storName,
#RequestParam String storDesc,
#RequestParam Double storPrice,
#RequestPart MultipartFile storLogo,
#RequestParam String storEmail,
#RequestParam String storPhone
) {
Store store = new Store();
store.setStorName(storName);
store.setStorDesc(storDesc);
try {
store.setStorLogo(storLogo.getBytes());
} catch (IOException ex) {
Logger.getLogger(StoreController.class.getName()).log(Level.SEVERE, null, ex);
}
store.setStoreEmail(storEmail);
store.setStorePhone(storPhone);
storeService.save(store);
return "redirect:/show/" + store.getstoreid();
}
and am getting the file just well in the store object ,in the service
so i guess is miss configuring problem ,maybe in jparepository or hibernate
any idea

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 !!!!!

Get controller receives JSON with List<String> as null in Spring JPA

When I'm posting a new entity through Postman everything works fine and I get this as an answer:
{
"id": 3,
"ingredients": [
"Eggs",
"Oil"
]
}
But when I'm trying to get the existing entities in the database, the List< String > ingredients is returned as "null":
[
{
"id": 3,
"ingredients": null
}
]
Here is my model:
package com.petie.weeklyrecipesschedule.model;
import javax.persistence.*;
import java.util.List;
#Entity
public class Recipe {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private long id;
private String name;
#Embedded
private List<String> ingredients;
protected Recipe() {}
public Recipe(String name, List<String> ingredients) {
this.name = name;
this.ingredients = ingredients;
}
//Getters and setters
//toString()
}
My Repository
package com.petie.weeklyrecipesschedule.repository;
import com.petie.weeklyrecipesschedule.model.Recipe;
import org.springframework.data.jpa.repository.JpaRepository;
public interface RecipeRepository extends JpaRepository<Recipe, Long> {
}
And my controller
package com.petie.weeklyrecipesschedule.controller;
import com.petie.weeklyrecipesschedule.model.Recipe;
import com.petie.weeklyrecipesschedule.repository.RecipeRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
#RestController
#RequestMapping("/recipes")
public class RecipeController {
#Autowired
private RecipeRepository recipeRepository;
public RecipeController(RecipeRepository recipeRepository) {
this.recipeRepository = recipeRepository;
}
#GetMapping("/all")
List<Recipe> getAll() {
return recipeRepository.findAll();
}
#PostMapping("/post")
Recipe newRecipe(#RequestBody Recipe recipe) {
return recipeRepository.save(recipe);
}
}
As far as dependencies go, I'm using Spring Web, Spring Jpa, and H2 database.
You can also use #ElementCollection:
#ElementCollection
#CollectionTable(name = "recipe_ingredients",
joinColumns = #JoinColumn(name = "recipe_id"))
#Column(name = "ingredient_name")
private List<String> ingredients;
The JPA annotation #Embedded is used to embed a type into another entity.
Note: In addition, you don't need to send an id in your post request, it will be created automatically.

Spring boot application executes without any error but not creating any tables in the backend

I have created a spring boot and RestAPI application project. Everything runs and executes but it is not creating any table in the backend (MySQL). It is not showing any error in the console too. I am new to spring boot and APIs.
Below is the code in my:
application.properties :
spring.jpa.hibernate.ddl-auto=update
spring.datasource.url=jdbc:mysql://localhost:3306/EjikeDB?createDatabaseIfNotExist=true&&autoReconnect=true&verifyServerCertificate=false&useSSL=false&requireSSL=false serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=MacRoot31
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5InnoDBDialect
spring.jpa.generate-ddl=true
spring.jpa.show-sql=true
spring.datasource.initialization-mode=always
########### SMTP Email Properties ###################
spring.mail.host=smtp.mailtrap.io
spring.mail.port=465
spring.mail.username=f26e44090838e5
spring.mail.password=b2a684f17dbfc2
spring.mail.protocol=smtp
############ JWT Properties #####################
jwt.expiration.time=90000
and
User.java :
import java.util.List;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.validation.constraints.NotBlank;
import java.time.Instant;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
//#EnableAutoConfiguration
#EntityScan
#Data
#AllArgsConstructor
#NoArgsConstructor
#Entity
#Table(name = "MarketplaceUser")
public class User {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private int userid;
private String firstname;
private String lastname;
#NotBlank(message = "Username is required")
private String userName;
#NotBlank(message = "Email is required")
private String email;
#NotBlank(message = "Password is required")
private String password;
private String phoneNumber;
private String country;
private String provinceState;
private String city;
private String street;
#NotBlank(message = "Postcode is required")
private String postalCode;
private String roles;
#OneToMany(mappedBy = "user")
private List<Product> product;
private Instant created;
private boolean enabled;
}
I tried adding the spring.jpa.hibernate.ddl-auto=update
and
spring.jpa.hibernate.ddl-auto=create both
aswell as
createDatabaseIfNotExist=true&&autoReconnect=true&verifyServerCertificate=false&useSSL=false&requireSSL=false to my application.properties file.
But nothing changed. And the main issue being there's no error displayed in the console.
This is the project structure. If in case there's any error in this.
Recently I had same issue that spring wasn't creating mysql tables, but this line in application.properties fixed it
spring.jpa.hibernate.ddl-auto = create
Is your entity class in the same package or a relative one where you have the main spring class (the one you add the #EnableAutoConfiguration)? If not, spring probably won't find it. And this is leading to your program being executed but nothing being created in DB.

How to correct sql statement to give correct result

I'm running a local MySQL Server on port 3306 with a schema "sys" featuring a table "users"
Now I have a small spring boot application to query all entries from that table.
Model for that table is:
package com.example.databaseneu.model;
import javax.persistence.Entity;
import javax.persistence.Id;
#Entity
public class Users {
#Id
// #Column(name = "id")
private int id;
// #Column(name = "name")
private String name;
// #Column(name = "salary")
private int salary;
// #Column(name = "team_name")
private String team_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 int getSalary() {
return salary;
}
public void setSalary(int salary) {
this.salary = salary;
}
public String getTeam_name() {
return team_name;
}
public void setTeam_name(String team_name) {
this.team_name = team_name;
}}
The connection works, but the query doesnt seem to deliver the right result as I get the Whitelabel Error Page.
Query to get all elements from the table (autogenerated by repository)
Hibernate:
select
users0_.id as id1_0_,
users0_.name as name2_0_,
users0_.salary as salary3_0_,
users0_.team_name as team_nam4_0_
from
users users0_
So I'm uncertain if i defined the Entity wrong or something else alltogether
#Column Tag doesnt do the trick.
---Edit---
package com.example.databaseneu.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.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.example.databaseneu.model.Users;
import com.example.databaseneu.repository.UserRepository;
#Controller // This means that this class is a Controller
#RequestMapping(path = "/demo") // This means URL's start with /demo (after Application path)
public class MainController {
#Autowired
private UserRepository userRepository;
#GetMapping(path = "/add")
public #ResponseBody String addNewUser(#RequestParam String name, #RequestParam int salary,
#RequestParam String team_name) {
Users n = new Users();
n.setName(name);
n.setSalary(salary);
n.setTeam_name(team_name);
userRepository.save(n);
return "Saved";
}
#GetMapping(path = "/all")
public Iterable<Users> getAllUsers() {
return userRepository.findAll();
}}
So id navigate to localhost:8080/demo/all
You have written all correct expect for one thing. Mark your return-type with #ResponseBody annotation -- similar to your addNewUser method.
#GetMapping(path = "/all")
public #ResponseBody Iterable<Users> getAllUsers() {
return userRepository.findAll();
}}
Hopefully this should work. If you still face issues, post it here.

Getting data from database

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());
}
}