how to store and retrieve image files from database using springboot - database

I'm building an angular springboot application but I find so many approaches to do this some of which I honestly do not understand.
how can I store 1 or more images at a time and retrieve them.

You can use #Lob to store Images or Any Files in the Database. The following example shows a simple implementation of this approach
#Entity
#Table(name = "file")
public class File {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#Column(name = "uuid")
private String uuid;
#Column(name = "content_type")
private String contentType;
#Column(name = "extension")
private String extension;
#Lob
#Column(name = "content", columnDefinition = "LONGBLOB")
private byte[] content;
}
#Service
public class FileService {
private final FileRepository repository;
#Autowired
public FileService(FileRepository repository) {
this.repository = repository;
}
#Transactional
public StreamingResponseBody download(Long id, HttpServletResponse response) {
final File file = repository.findById(id).orElseThrow(NotFoundException::new);
return outputStream -> {
String fileName = (file.getUuid() + file.getExtension()).trim();
response.setContentType(file.getContentType());
response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
outputStream.write(file.getContent());
outputStream.flush();
};
}
public FileDto create(MultipartFile multipartFile, boolean general) {
String fileName = multipartFile.getOriginalFilename();
String fileExtension = Objects.requireNonNull(fileName).substring(fileName.lastIndexOf('.'));
String uuid = UUID.randomUUID().toString();
UserDto user = contextUtils.getPrincipal();
File file = new File();
file.setUuid(uuid);
file.setContentType(multipartFile.getContentType());
file.setExtension(fileExtension);
file.setGeneral(general);
file.setContent(multipartFile.getBytes());
file.setId(repository.save(file).getId());
return file;
}
}

Related

Cannot Convert String to Timespamp inside REST

Hello:) i really hope i can find help here!
the Problem: Im using Spring JPA, have created a basic REST Service, i added my Database, and i can find data in the databaste via entitymanager.createQuery()
BUT when i try to search for a timestamp or a datetime, it gives me this error:
15:12 SELECT b FROM StationsMessung b WHERE b.AVNR=:AVNR AND
b.TXNR=:TXNR AND b.DBTM=:DATUM
java.lang.ClassCastException: java.lang.String cannot
be cast to java.util.Date
at org.hibernate.type.descriptor.java.JdbcTimestampTypeDescriptor.unwrap(JdbcTimestampTypeDescriptor.java:24)
at org.hibernate.type.descriptor.sql.TimestampTypeDescriptor$1.doBind(TimestampTypeDescriptor.java:48)
at org.hibernate.type.descriptor.sql.BasicBinder.bind(BasicBinder.java:74)
at org.hibernate.type.AbstractStandardBasicType.nullSafeSet(AbstractStandardBasicType.java:280)
at org.hibernate.type.AbstractStandardBasicType.nullSafeSet(AbstractStandardBasicType.java:275)
at org.hibernate.param.NamedParameterSpecification.bind(NamedParameterSpecification.java:53)
at org.hibernate.loader.hql.QueryLoader.bindParameterValues(QueryLoader.java:628)
at org.hibernate.loader.Loader.prepareQueryStatement(Loader.java:2001)
at
org.hibernate.loader.Loader.executeQueryStatement(Loader.java:1915)
at org.hibernate.... (show balloon)
i know it says it cannot convert String to java.util.Date, but i dont know how to solve it.thanks for every helper!
/////////////////////////////////////////////////////////ENTITY CLASS
#Entity
#IdClass(StationsMessung.class)
#Table(name = "****", schema = "***")
public class StationsMessung implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "AVNR")
private int AVNR; ////
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "TXNR")
private int TXNR;
#GeneratedValue(strategy = GenerationType.AUTO)
#Temporal(TemporalType.TIMESTAMP)
#Type(type = "date")
#Column(name = "DBTM")
private Timestamp DBTM;
public StationsMessung(int AVNR, int TXNR, Timestamp DBTM) {
this.AVNR = AVNR;
this.TXNR = TXNR;
this.DBTM = DBTM;
}
public StationsMessung() {
}
public int getAvnr() {
return AVNR;
}
public void setAvnr(int AVNR) {
this.AVNR = AVNR;
}
public int getTxnr() {
return TXNR;
}
public void setTxnr(int TXNR) {
this.TXNR = TXNR;
}
public Timestamp getDBTM() {
return DBTM;
}
public void setDBTM(Timestamp DBTM) {
this.DBTM = DBTM;
}
///////////////////////////////////////////////////////////SERVICE CLASS
#Service
public class StationService {
#PersistenceContext
EntityManager entityManager;
public List<Station> getAllStationMessungen(int AVNR, int TXNR, Timestamp DATUM) {
return entityManager.createQuery("SELECT b FROM StationsMessung b WHERE b.AVNR=:AVNR AND b.TXNR=:TXNR AND b.DBTM=:DATUM")
.setParameter("TXNR",TXNR )
.setParameter("AVNR",AVNR )
.setParameter("DATUM", DATUM)
.getResultList();
}
////////////////////////////////////////////////////////////CONTROLER CLASS
#RestController
#RequestMapping("/station")
public class StationController {
#Autowired //This annotation allows Spring to resolve and inject
collaborating beans into your bean
StationService stationService; //service
#RequestMapping(value = "/allmessungen/{AVNR}/{TXNR}/{DATUM}", method =
RequestMethod.GET)
public List<Station> getAllStationMessungen(#PathVariable int AVNR, int
TXNR, Timestamp DATUM) {
return stationService.getAllStationMessungen( AVNR, TXNR, DATUM);
}
now when i search for data without the timestamp,it shows me data,it works.
when i use a timestamp or date it shows me the error above.
THE INPUT OF ME IS:
PARAM.1 AVNR: 716
PARAM.2 TXNR: 1339
PARAM.3 DBTM: 2014-01-04 05:30:00
(its this format yyyy-mm-dd-hh24:mi:ss)
thanks for every help:)

Spring-boot & multiple database connections: autowire service does not work

I'm writing an Spring-boot application that needs to connect to at least 2 databases.
I have 1 project per database in order to define their domains, 1 project per database in order to define their services and 1 Vaadin project for the UI.
- a business domain entity sample
#Entity
#Table(name="T_PARAMETER")
public class Parameter extends BaseIdEntity implements Serializable {
#Column(name="par_cls")
#NotNull
private String parameterClass;
#Column(name="par_cd")
#NotNull
private String parameterCode;
#Column(name="par_lan")
#NotNull
private String language;
#Column(name="par_sht_val")
#NotNull
private String parameterValueShort;
#Column(name="par_lng_val")
#NotNull
private String parameterValueLong;
- a authentication domain entity sample
#Entity
#Table(name="t_user", schema="authenticate")
public class User extends BaseIdEntity implements Serializable {
#Id
#Column(name="user_cd")
private String userCode;
#Column(name="pwd")
#NotNull
private String password;
#Column(name="new_pwd_req")
#NotNull
private boolean passwordRequired;
#Column(name="acc_lck")
#NotNull
private boolean accountLocked;
There are repositories onto these 2 entities beans, they just extends the JpaRepository as hereunder:
public interface ParameterRepository extends JpaRepository<Parameter,Integer>{}
the services are defined as hereunder:
#Service
#Transactional(transactionManager="authenticateTransactionManager")
public class ServiceParameterImpl implements ServiceParameter {
private final static Logger log = LoggerFactory.getLogger(ServiceParameterImpl.class);
#Autowired
private ParameterRepository parameterRepository;
#Override
#Transactional(readOnly=true,transactionManager="authenticateTransactionManager")
public List<Parameter> findParameterHeader(String filter) {
.../...
The client application as:
#SpringBootApplication
#Configuration
#EnableAutoConfiguration(exclude = { DataSourceAutoConfiguration.class
, HibernateJpaAutoConfiguration.class
, DataSourceTransactionManagerAutoConfiguration.class })
#ComponentScan(
basePackages= {
"org.associative.ui"
,"org.associative.service"
})
#Import({AssociativityConfiguration.class, AuthenticateConfiguration.class})
public class Application {
private final static Logger log = LoggerFactory.getLogger(Application.class);
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
and configurations:
#Configuration
#EnableTransactionManagement
#EntityScan(basePackages= "org.associative.domain.associativity")
#EnableJpaRepositories(
basePackages = "org.associative.domain.associativity.repository"
, entityManagerFactoryRef = "associativityEntityManager"
, transactionManagerRef = "associativityTransactionManager"
)
#ConfigurationProperties(prefix = "db.associativity")
public class AssociativityConfiguration {
private final static Logger log = LoggerFactory.getLogger(AssociativityConfiguration.class);
#Autowired
private Environment env;
private final static String ASSOCIATIVITY_DRIVER_CLASS_NAME = "db.associativity.classname";
private final static String ASSOCIATIVITY_URL = "db.associativity.connectionUrl";
private final static String ASSOCIATIVITY_USERNAME = "db.associativity.username";
private final static String ASSOCIATIVITY_PASSWORD = "db.associativity.password";
private final static String HIBERNATE_DIALECT = "hibernate.dialect";
#Bean(name = "associativityDataSource")
public DataSource datasource() {
DataSource dataSource = DataSourceBuilder.create()
.driverClassName(env.getProperty(ASSOCIATIVITY_DRIVER_CLASS_NAME))
.url(env.getProperty(ASSOCIATIVITY_URL))
.username(env.getProperty(ASSOCIATIVITY_USERNAME))
.password(env.getProperty(ASSOCIATIVITY_PASSWORD)).build();
if (log.isTraceEnabled())
log.trace(String.format("associativityConfiguration datasource:%s", dataSource.toString()));
return dataSource;
}
#Bean(name = "associativityEntityManager")
#PersistenceContext(unitName = "associativity")
public LocalContainerEntityManagerFactoryBean entityManagerFactory(
EntityManagerFactoryBuilder builder,
#Qualifier("associativityDataSource") DataSource dataSource) {
Map<String, Object> jpaProperties = new HashMap<>();
jpaProperties.put(HIBERNATE_DIALECT, env.getProperty(HIBERNATE_DIALECT));
LocalContainerEntityManagerFactoryBean em = builder.dataSource(dataSource)
.packages("org.associative.domain.authenticate").persistenceUnit("pu_associativity").properties(jpaProperties)
.build();
em.setJpaPropertyMap(jpaProperties);
HibernateJpaVendorAdapter adapter = new HibernateJpaVendorAdapter();
em.setJpaVendorAdapter(adapter); // not mandatory definition
return em;
}
#Bean(name = "associativityTransactionManager")
public PlatformTransactionManager associativityTransactionManager(
#Qualifier("associativityEntityManager") EntityManagerFactory entityManagerFactory) {
JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(entityManagerFactory);
return transactionManager;
}
}
and
#Configuration
#EnableTransactionManagement
#EntityScan(basePackages= "org.associative.domain.authenticate")
#EnableJpaRepositories(
basePackages = "org.associative.domain.authenticate.repository"
, entityManagerFactoryRef = "authenticateEntityManager"
, transactionManagerRef = "authenticateTransactionManager"
)
#ConfigurationProperties(prefix="db.authenticate")
public class AuthenticateConfiguration {
private final static Logger log = LoggerFactory.getLogger(AuthenticateConfiguration.class);
#Autowired
private Environment env;
private final static String AUTHENTICATE_DRIVER_CLASS_NAME= "db.authenticate.classname";
private final static String AUTHENTICATE_URL = "db.authenticate.connectionUrl";
private final static String AUTHENTICATE_USERNAME = "db.authenticate.username";
private final static String AUTHENTICATE_PASSWORD = "db.authenticate.password";
private final static String HIBERNATE_DIALECT = "hibernate.dialect";
#Primary
#Bean(name = "authenticateDataSource")
public DataSource datasource() {
DataSource dataSource = DataSourceBuilder.create()
.driverClassName(env.getProperty(AUTHENTICATE_DRIVER_CLASS_NAME))
.url(env.getProperty(AUTHENTICATE_URL))
.username(env.getProperty(AUTHENTICATE_USERNAME))
.password(env.getProperty(AUTHENTICATE_PASSWORD))
.build();
if ( log.isTraceEnabled()) log.trace(String.format("authenticateDataSource datasource:%s", dataSource.toString()));
return dataSource;
}
#Primary
#Bean(name="authenticateEntityManager")
#PersistenceContext(unitName = "authenticate")
//https://raymondhlee.wordpress.com/tag/enablejparepositories/
public LocalContainerEntityManagerFactoryBean entityManagerFactory(
EntityManagerFactoryBuilder builder, #Qualifier("authenticateDataSource")DataSource dataSource) {
Map<String,Object> jpaProperties = new HashMap<>();
jpaProperties.put(HIBERNATE_DIALECT, env.getProperty(HIBERNATE_DIALECT));
LocalContainerEntityManagerFactoryBean em = builder
.dataSource(dataSource)
.packages("org.associative.domain.authenticate")
.persistenceUnit("pu_authenticate")
.properties(jpaProperties)
.build();
em.setJpaPropertyMap(jpaProperties);
HibernateJpaVendorAdapter adapter = new HibernateJpaVendorAdapter();
em.setJpaVendorAdapter(adapter); // not mandatory definition
return em;
}
#Primary
#Bean(name="authenticateTransactionManager")
public PlatformTransactionManager authenticateTransactionManager(
#Qualifier("authenticateEntityManager")EntityManagerFactory entityManagerFactory){
JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(entityManagerFactory);
return transactionManager;
}
}
I'm facing an issue when a service is built by using autowiring in the construction of my client interface:
#SpringUI
public class ParameterListView extends CssLayout implements Serializable {
private final static Logger log = LoggerFactory.getLogger(ParameterListView.class);
#Autowired
private ParameterController controller;
#PostConstruct
private void initView() {
if ( log.isTraceEnabled() ) log.trace(String.format("initView:%s", "no param"));
Grid<Parameter> grid = new Grid<>();
this.addComponent(grid);
grid.setItems(controller.getParameterHeader(""));
grid.addColumn(Parameter::getParameterClass);
grid.addColumn(Parameter::getParameterValueShort);
grid.addColumn(Parameter::getParameterValueLong);
2017-12-01 14:20:07.151 ERROR o.s.b.SpringApplication Application startup failed
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'parameterControllerImpl': Unsatisfied
dependency expressed through field 'serviceParameter'; nested
exception is
org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name 'serviceParameterImpl': Unsatisfied
dependency expressed through field 'parameterRepository'; nested
exception is org.springframework.beans.factory.BeanCreationException:
Error creating bean with name 'parameterRepository': Invocation of
init method failed; nested exception is
java.lang.IllegalArgumentException: Not a managed type: class
org.associative.domain.associativity.Parameter
I already spent a lot of time in order to solve the multiple database connections because I was thinking this issue comes from a definition problem but I'm not sure now.
So, what should I look to in order to solve this.
Thank you very much.
The last line of your stack trace is a clue: Not a managed type: class org.associative.domain.associativity.Parameter. Hibernate doesn't know about your Parameter entity.
In the LocalContainerEntityManagerFactoryBean you set packages to scan to org.associative.domain.authenticate. Your Parameter entity is not under this package.
This should fix the problem:
.packages("org.associative.domain.authenticate", "org.associative.domain.associativity")

Error in Many to one relation

My Organization entity
#Entity
public class Organization implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Key key;
private String name;
private String type;
private byte image;
#OneToMany(cascade=CascadeType.MERGE)
#JoinColumn(name="ORGANIZATION_ID")
private List<User> admin;
My User entity
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Key key;
private String score;
private boolean online;
private String resume;
public Status status;
public enum Status {
ACTIVE, INACTIVE, VERIFIED, NOT_VERIFIED , BANNED
};
#ManyToOne(cascade=CascadeType.MERGE)
#JoinColumn(name="ORGANIZATION_ID")
private Organization organization;
#Persistent
private User_personal user_p;
public User_personal getUser_personal(){
return user_p;
}
public void setUser_personal(User_personal user_p) {
this.user_p = user_p;
}
#OneToMany(mappedBy = "user", cascade=CascadeType.MERGE)
private List<Project> projects;
I got the one-Many relation between User and Projects correctly but not working for User and Organization(many-one).I am getting error like this
WARNING: /OrganizationServlet
javax.persistence.PersistenceException: Detected attempt to establish
Organization(no-id-yet) as the parent of User(4793870697103360) but the
entity identified by User(4793870697103360) has already been persisted
without a parent. A parent cannot be established or changed once an object
has been persisted.at...
showing error at em.getTransaction().commit();.
My servlet is
protected void doPost(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException {
// TODO Auto-generated method stub
HashMap<String,String> map = Request_to_map.getBody(request);
boolean validToken = JWT.parseJWT(request.getHeader("Access-token")
,map.get("email"));
JsonObject output = new JsonObject();
List<User> organization_admin = new ArrayList<User>();
if(validToken == true){
EntityManager em;
em = EMF.get().createEntityManager();
String organizationName = map.get("name");
String type = map.get("type");
byte image = 0;
if(map.get("image")!=null)
{
image = Byte.valueOf(map.get("image"));
}
String email = map.get("email");
if(organizationName==null||type==null||email==null||map.get("image")==null)
{
throw new IllegalArgumentException("please fill required
details");
}
try{
em.getTransaction().begin();
User user = User.find(email, em);
if(user!=null)
{
Organization.org_status status= org_status.ACTIVE;
Organization organization = new
Organization(organizationName, type,image,status);
user.setOrganization(organization);
organization_admin = organization.getAdmin();
if(organization_admin == null)
{
organization_admin = new ArrayList<User>();
}
organization_admin .add(user);
organization.setAdmin(organization_admin);
em.persist(organization);
em.persist(user);
output.addProperty("message", "done");
em.getTransaction().commit();
}
else
output.addProperty("message","No such User found.Please
check details provided");
}
finally{
if(em.getTransaction().isActive())
em.getTransaction().rollback();
// em.close();
}
}
else
output.addProperty(Constants.MESSAGE,
Constants.TokenNotAuthenticated);
response.setContentType("application/Json");
response.getWriter().println(output);
}
Can anyone help me in getting this? When user is created I am getting ORGANIZATION_ID as a column but cant create entity of organization.I dont think joins are to be used as GAE doesn't allow it.

Read JSON Request and Map to JAVA POJO

My Requirement:
I have a JSON request in a table column which is like below.
{
"customerData": [{ "primaryData":[ {
"HNo": "8-10-2",
"APTNM": "SRSENCLAVE",
"STRT": "MGCLNY"
}],
"officeData":{
"ADDR": "1/7-25",
"STRT": "FINDIST",
"LM": "JBE"
},
"ContactData": {
"PHNO":"XXXXXXXXX",
"ZIP":"XXXXXX",
"MAILCD": "XXXX"},
}
]}
I need to read it from DB and map the JSON values into three different class properties.i.e. PrimaryData.java. OfficeData.java,ContactData.java.
I'm able to successfully read the request from DB but struck on how to map the values to properties in my three POJO classes. I tried using faster xml, google Gson, org.json but I could not get it well. Can someone give me an idea or part of code snippet?
How I'm trying to achieve above (not sure if this approach is correct at all)
List<Map<String, PrimaryData>> cxData = new ArrayList<Map<String,PrimaryData>>();
JSONObject jSONObject = new JSONObject(query.getResultList().get(0).toString());
JSONArray jsonArray = jSONObject.getJSONArray("customerData");
int length = jsonArray.length();
for (int i=0; i<length; i++)
{
// FOR EACH ENTRY
JSONObject OneEntry = jsonArray.getJSONObject(i);
int OneEntrySize = OneEntry.length();
JSONArray EntKey = OneEntry.names();
Map<String, PrimaryData> map = new HashMap<String, PrimaryData>();
for (int j=0; j<OneEntrySize;j++)
{ // FOR EACH ITEM IN AN ENTRY
String key = EntKey.getString(j);
PrimaryData val = (PrimaryData)OneEntry.opt(key);;--unable to cast (can not cast JsonArray to PrimaryData)
map.put(key, val);
}
cxData.add(map);
}
With GSON
public class Data {
#SerializedName("customerData") #Expose private List<CustomerData> customerData = null;
}
public class CustomerData {
#SerializedName("primaryData") #Expose private List<PrimaryData> primaryData = null;
#SerializedName("officeData") #Expose private OfficeData officeData;
#SerializedName("ContactData") #Expose private ContactData contactData;
}
public class PrimaryData {
#SerializedName("HNo") #Expose private String hNo;
#SerializedName("APTNM") #Expose private String aPTNM;
#SerializedName("STRT") #Expose private String sTRT;
}
public class OfficeData {
#SerializedName("ADDR") #Expose private String aDDR;
#SerializedName("STRT") #Expose private String sTRT;
#SerializedName("LM") #Expose private String lM;
}
public class ContactData {
#SerializedName("PHNO") #Expose private String pHNO;
#SerializedName("ZIP") #Expose private String zIP;
#SerializedName("MAILCD") #Expose private String mAILCD;
}
Gson gson = new Gson();
Data data = gson.fromJson(dataJSON, Data.class);

hibernate criteria if collection contains collection

I have a Priv class
#Entity
#Table(name = "PK_PRIVS", schema = "dbo")
public class Priv implements java.io.Serializable{
private static final long serialVersionUID = 1L;
private String code;
private String name;
private String description;
private PrivType type;
//...
}
and a Report class which has many to many relation with Priv and contains Set of associated Privs - privs.
#Entity
#Table(name = "REPORT", schema = "dbo")
public class Report implements java.io.Serializable {
//...
private Set<Priv> privs = new HashSet<Priv>(0);
//...
#JsonIgnore
#ManyToMany(fetch = FetchType.LAZY)
#JoinTable(name = "REPORT_PK_PRIVS", schema = "dbo", joinColumns = { #JoinColumn(name = "REPORT_ID") }, inverseJoinColumns = { #JoinColumn(name = "PK_PRIVS_CODE") })
public Set<Priv> getPrivs() {
return this.privs;
}
public void setPrivs(Set<Priv> privs) {
this.privs = privs;
}
}
Now I have a Set of Strings, which are codes of Priv classes (code is Primary Key in Priv).
Set<String> privsCodesSet; //set of codes of Priv classes
I need a criterion which allow me to find that Reports, which all codes from its Priv set contains in privsCodesSet. For example if I have privsCodeSet = {"code1", "code2"}
Report with privs with codes {"code1"" should be in result, but
Report with privs with codes {"code1", "code2", "code3"} should not.
I also have class which is join of Priv and Report, but I'm not sure if it's help.
This code should work
Criteria reportPrivCriteria = currentSession()
.createCriteria( Report.class, "r");
reportPrivCriteria.createAlias("privs", "p");
reportPrivCriteria.add(Restrictions.in(p.code, privsCodeSet));
Do you have something like this on your Priv class?
private Set<Report> reports;
// ...
#ManyToMany(mappedBy="privs")
public Collection<Report> getReports() {
return reports;
}

Resources