I can not fix the error when creating Room Database in Android Studio. Error: stmt.bindLong(1, value.ID);
Also in the database sql queries: "notes", "title", "id" are highlighted in red, as if there is an error here. When trying to compile, it transfers to a file - MainDAO_Impl.java. Shown in the screenshotRoom code:
package com.example.applicationnotes.DataBase;
import android.content.Context;
import androidx.room.Database;
import androidx.room.Room;
import androidx.room.RoomDatabase;
import com.example.applicationnotes.Models.Notes;
#Database(entities = Notes.class, version = 1, exportSchema = false)
public abstract class RoomDB extends RoomDatabase {
private static RoomDB database;
private static String DATABASE_NAME = "NoteApp";
public synchronized static RoomDB getInstance(Context context){
if (database == null) {
database = Room.databaseBuilder(context.getApplicationContext(),
RoomDB.class, DATABASE_NAME)
.allowMainThreadQueries()
.fallbackToDestructiveMigration()
.build();
}
return database;
}
public abstract com.example.applicationnotes.DataBase.MainDAO mainDao();
}
MainDAO:
package com.example.applicationnotes.DataBase;
import static androidx.room.OnConflictStrategy.REPLACE;
import androidx.room.Dao;
import androidx.room.Delete;
import androidx.room.Insert;
import androidx.room.Query;
import java.util.List;
import com.example.applicationnotes.Models.Notes;
#Dao
public interface MainDAO {
#Insert (onConflict = REPLACE)
void insert (Notes notes);
#Query ("SELECT * FROM notes ORDER BY id DESC")
List<Notes> getAll();
#Query("UPDATE notes SET title = :title, notes = :notes WHERE ID = :id")
void update (int id, String title, String notes);
#Delete
void delete (Notes notes);
#Query("UPDATE notes SET pinned = :pin WHERE ID = :id")
void pin (int id, boolean pin);
}
More in screenshot:-
https://i.stack.imgur.com/fEkRg.png
https://i.stack.imgur.com/VxDll.png
I tried to change requests, selectors, file names, rummaged through the SQL forums, did not find a solution to my particular problem.
Screenshots with error and SQL-request:
https://i.stack.imgur.com/fEkRg.png
https://i.stack.imgur.com/VxDll.png
I believe that you have removed the member ID from Notes (or possibly removed the Class entirely) and without then compiling the project looked at the MainDAO_Impl.
For example consider:-
#Entity
class Notes {
#PrimaryKey(autoGenerate = true)
long ID;
String title;
String notes;
String date;
boolean pinned;
}
After compiling then MainDAO_Impl is:-
Now if Notes is changed to (long ID; commented out):-
#Entity
class Notes {
#PrimaryKey(autoGenerate = true)
//long ID; /*<<<<<<<<<< COMMENTED OUT >>>>>>>>>>*/
String title;
String notes;
String date;
boolean pinned;
}
Then without compiling MainDAO_Impl is:-
First time trying out GraphQL, so please excuse if it is a basic fix.
https://i.stack.imgur.com/Hwf8Q.png
My API is used to show some mock data of departures from Heathrow. The API should return all the departures which are displayed in the import.sql file. This is running a h2 in memory DB using Spring. My application.properites:
spring.h2.console.enabled=true
spring.h2.console.path=/h2
spring.datasource.url=jdbc:h2:mem:lhrdata
graphql.servlet.mapping=/graphql
graphql.servlet.enabled=true
graphql.servlet.corsEnabled=true
graphiql.enabled=true
graphiql.endpoint=/graphql
graphiql.mapping=graphiql
spring.datasource.username=sa
spring.datasource.password=
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.format_sql=true
spring.jpa.defer-datasource-initialization=true
Entity > Departure.java
package com.LHRDepartures.LHROUT.entity;
import javax.persistence.*;
import java.util.Arrays;
import java.util.List;
#Entity
public class Departure {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String destination;
private Float arrival_time;
private String airline;
private String aircraft_make;
private String aircraft_model;
private String terminal;
public Departure() {
}
public Departure(Long id, String destination, Float arrival_time, String airline, String aircraft_make, String aircraft_model, String terminal) {
this.id = id;
this.destination = destination;
this.arrival_time = arrival_time;
this.airline = airline;
this.aircraft_make = aircraft_make;
this.aircraft_model = aircraft_model;
this.terminal = terminal;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getDestination() {
return destination;
}
public void setDestination(String destination) {
this.destination = destination;
}
public Float getArrival_time() {
return arrival_time;
}
public void setArrival_time(Float arrival_time) {
this.arrival_time = arrival_time;
}
public String getAirline() {
return airline;
}
public void setAirline(String airline) {
this.airline = airline;
}
public String getAircraft_make() {
return aircraft_make;
}
public void setAircraft_make(String aircraft_make) {
this.aircraft_make = aircraft_make;
}
public String getAircraft_model() {
return aircraft_model;
}
public void setAircraft_model(String aircraft_model) {
this.aircraft_model = aircraft_model;
}
public String getTerminal() {
return terminal;
}
public void setTerminal(String terminal) {
this.terminal = terminal;
}
}
Mutator
package com.LHRDepartures.LHROUT.mutator;
import com.LHRDepartures.LHROUT.entity.Departure;
import com.LHRDepartures.LHROUT.exception.DepartureNotFoundException;
import com.LHRDepartures.LHROUT.repository.DepartureRepository;
import com.coxautodev.graphql.tools.GraphQLMutationResolver;
import org.springframework.stereotype.Component;
import java.util.Optional;
public class Mutation implements GraphQLMutationResolver {
private DepartureRepository departureRepository;
public Mutation(DepartureRepository departureRepository){
this.departureRepository = departureRepository;
}
public boolean deleteDeparture(Long ID){
departureRepository.deleteById(ID);
return true;
}
/*
public Departure updateTerminal(Integer newTerminal, Long Id){
Optional<Departure> optionalDeparture =
departureRepository.findById(Id);
if(optionalDeparture.isPresent()){
Departure departure = optionalDeparture.get();
// departureRepository.setName(newTerminal);
departureRepository.save(departure);
return departure;
} else {
throw new DepartureNotFoundException("Departure not found!", Id);
} */
}
Repository
package com.LHRDepartures.LHROUT.repository;
import com.LHRDepartures.LHROUT.entity.Departure;
import org.springframework.data.repository.CrudRepository;
public interface DepartureRepository extends CrudRepository<Departure, Long> {
}
Query
package com.LHRDepartures.LHROUT.resolver;
import com.LHRDepartures.LHROUT.entity.Departure;
import com.LHRDepartures.LHROUT.repository.DepartureRepository;
import org.springframework.stereotype.Component;
#Component
public class Query {
private DepartureRepository departureRepository;
public Query(DepartureRepository departureRepository){
this.departureRepository = departureRepository;
}
public Iterable<Departure> findAllDepartures() {
return departureRepository.findAll();
}
}
Service
package com.LHRDepartures.LHROUT.service;
import com.LHRDepartures.LHROUT.entity.Departure;
import org.springframework.stereotype.Service;
import java.util.List;
public interface DepartureService {
List<Departure> retrieveDeparture();
}
Controller
package com.LHRDepartures.LHROUT.web;
import com.LHRDepartures.LHROUT.entity.Departure;
import com.LHRDepartures.LHROUT.service.DepartureService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
#RestController
public class DepartureController {
private DepartureService departureService;
#Autowired
public void setDepartureService(DepartureService departureService){
this.departureService = departureService;
}
#GetMapping("/departure")
public ResponseEntity<List<Departure>> getAllDeparture(){
List<Departure> list = departureService.retrieveDeparture();
return new ResponseEntity<List<Departure>>(list, HttpStatus.OK);
}
}
GraphQL schema:
type Departure{
id: ID!
destination : String!
arrival_time : Float!
airline : String!
aircraft_make : String
aircraft_model : String
terminal : String!
}
type Query {
findAllDepartures: [Departure]
}
type Mutation {
deleteDeparture(id:ID) : Boolean
updateTerminal(newTerminal : String, id:ID!): Departure!
}
Import.sql
INSERT INTO departure (id, destination, arrival_time, airline, aircraft_make, aircraft_model, terminal) VALUES (1, 'LAX - Los Angeles Intl.', '1234', 'British Airways', 'AIRBUS', 'A380', '5');
INSERT INTO departure (id, destination, arrival_time, airline, aircraft_make, aircraft_model, terminal) VALUES (2, 'JFK - New York John F. Kennedy Intl.', '1345', 'British Airways', 'BOEING', '777-300', '5');
INSERT INTO departure (id, destination, arrival_time, airline, aircraft_make, aircraft_model, terminal) VALUES (3, 'MAN - Manchester Intl.', '1400', 'British Airways', 'AIRBUS', 'A319', '5');
INSERT INTO departure (id, destination, arrival_time, airline, aircraft_make, aircraft_model, terminal) VALUES (4, 'FRA - Frankfurt Intl.', '1521', 'Lufthansa', 'AIRBUS', 'A319', "3');
INSERT INTO departure (id, destination, arrival_time, airline, aircraft_make, aircraft_model, terminal) VALUES (5, 'CPT - Cape Town Intl.', '1605', 'Virgin Atlantic', 'BOEING', '787-900', '2');
INSERT INTO departure (id, destination, arrival_time, airline, aircraft_make, aircraft_model, terminal) VALUES (6, 'LAX - Los Angeles Intl.', '1634', 'British Airways', 'BOEING', '777-300', '5');
I know there's a lot there, but I'm quite stuck. Any help appreciated.
At the moment you have no code that will glue your graphql server and business logic together.
Fortunately, Spring boot provides seamless integration GraphQL integration with their Spring Boot for GraphQL project.
In order to start using it, just add the following dependency to your build tool.
implementation 'org.springframework.boot:spring-boot-starter-graphql'
Then, you need to add your schema to the following place:
resources/graphql/schema.graphqls
Your schema definition looks good, so it will work when added into this place
Lastly, you need to define a Controller which will bind your business logic to the graphql server.
import com.example.graphql.departure.model.Departure;
import com.example.graphql.departure.model.DepartureRepository;
import org.springframework.graphql.data.method.annotation.QueryMapping;
import org.springframework.stereotype.Controller;
#Controller
public class DepartureController {
private final DepartureRepository departureRepository;
public DepartureController(DepartureRepository departureRepository) {
this.departureRepository = departureRepository;
}
#QueryMapping
public Iterable<Departure> findAllDepartures() {
return departureRepository.findAll();
}
}
Check how #QueryMapping annotation is used in order to define a valid graphql query.
Then, if you run everything, you should be able to see the results.
Take a look at this sample project for a reference https://github.com/CaptainAye/graphql-sample
Hello guys I need help to create a query to use in my #Repository.
This is the sql query consult
select * from sig_versions where sft_product_name like 'kiadoc-desktop' order by created_date DESC limit 1;
And this is the output
I don't know how to create the hibernate query using Hibernate and criteria
Now how can I call this from my #Repository
public String getSoftwareVersion(String name) throws InternalErrorException {
logger.info("getSoftwareVersion " + name);
Criteria criteria = this.sessionFactory.getCurrentSession().createCriteria(this.typeParameterClass);
criteria.add(Restrictions.eq("sft_product_name", name));
return ((SoftwareVersion) criteria.uniqueResult()).get_Version();
}
I'm getting the InvocationTargetException
These are my files
package ar.com.lakaut.sig.core.dao;
import ar.com.lakaut.sig.core.domain.SoftwareVersion;
import com.curcico.jproject.core.exception.InternalErrorException;
import org.apache.log4j.Logger;
import org.hibernate.Criteria;
import org.hibernate.Query;
import java.util.List;
import com.curcico.jproject.core.daos.BaseAuditedEntityDaoImpl;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
#Repository
public class SoftwareVersionDaoImpl extends BaseAuditedEntityDaoImpl<SoftwareVersion> implements SoftwareVersionDao {
public SoftwareVersionDaoImpl() { super(); }
Logger logger = Logger.getLogger(getClass());
public String getSoftwareVersion(String name) throws InternalErrorException {
logger.info("getSoftwareVersion " + name);
Criteria criteria = this.sessionFactory.getCurrentSession().createCriteria(this.typeParameterClass);
criteria.add(Restrictions.eq("sft_product_name", name));
return ((SoftwareVersion) criteria.uniqueResult()).get_Version();
}}
And the entity
package ar.com.lakaut.sig.core.domain;
import com.curcico.jproject.core.entities.BaseAuditedEntity;
import org.hibernate.annotations.SQLDelete;
import org.hibernate.annotations.Where;
import javax.persistence.*;
import java.io.Serializable;
#Entity
#Table(name = "sig_versions")
#SQLDelete(sql="UPDATE sig_versions SET deleted = '1' WHERE version_id = ? and version = ?")
#Where(clause="deleted is null")
public class SoftwareVersion extends BaseAuditedEntity implements Serializable {
public SoftwareVersion() {}
private String product_name;
private String sft_version;
private String obs;
#Id
#SequenceGenerator(name = "id_generator", sequenceName = "sig_versions_config_seq", allocationSize = 1)
#GeneratedValue(generator = "id_generator", strategy =GenerationType.SEQUENCE)
#Column(name = "sft_id", unique = true, nullable = false)
public Integer getId() { return this.id; }
#Column(name = "sft_product_name", nullable = false)
public String getProductName() { return product_name; }
public void setProductName(String product_name) { this.product_name = product_name; }
#Column(name = "sft_version", nullable = false)
public String get_Version() { return sft_version; }
public void set_Version(String version) { this.sft_version = version; }
#Column(name = "sft_obs", nullable = false)
public String getObs() { return obs; }
public void setObs(String obs) { this.obs = obs; }
}
The #Service
package ar.com.lakaut.sig.core.service;
import ar.com.lakaut.sig.core.domain.SoftwareVersion;
import com.curcico.jproject.core.exception.BaseException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.curcico.jproject.core.services.BaseAuditedEntityServiceImpl;
import ar.com.lakaut.sig.core.dao.SoftwareVersionDao;
import org.apache.log4j.Logger;
#Service("SoftwareVersionService")
public class SoftwareVersionServiceImpl extends BaseAuditedEntityServiceImpl<SoftwareVersion, SoftwareVersionDao> implements SoftwareVersionService {
Logger logger = Logger.getLogger(SoftwareVersionServiceImpl.class);
#Override
public String getSoftwareVersion(String name) throws BaseException {
logger.info("softwareVersionId: " + name);
return dao.getSoftwareVersion(name);
}
}
The Service
package ar.com.lakaut.sig.core.service;
import ar.com.lakaut.sig.core.domain.SoftwareVersion;
import com.curcico.jproject.core.services.BaseAuditedEntityService;
import com.curcico.jproject.core.exception.BaseException;
public interface SoftwareVersionService extends BaseAuditedEntityService<SoftwareVersion> {
/**
* Params: name
* Return
* Throws BaseException
*/
public String getSoftwareVersion(String name) throws BaseException;
}
The DAO
package ar.com.lakaut.sig.core.dao;
import com.curcico.jproject.core.daos.BaseAuditedEntityDao;
import com.curcico.jproject.core.exception.BaseException;
import com.curcico.jproject.core.exception.InternalErrorException;
import ar.com.lakaut.sig.core.domain.SoftwareVersion;
public interface SoftwareVersionDao extends BaseAuditedEntityDao<SoftwareVersion>{
String getSoftwareVersion(String name) throws InternalErrorException;
}
I'm facing some problem with displaying COUNT of a variable while querying a MySQL database. I have made a variable with annotation #Transient so that it's not included in the DB. But, I'm getting error while posting data in the same table in the DB, since while posting, there is no field count, count is only used to get COUNT(u_type). Is there any way with which I can display COUNT of a variable when I do a GET call (using SQL query) and no need to post it. TIA.
Class:
import java.sql.Date;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import org.springframework.data.annotation.Transient;
#Entity // This tells Hibernate to make a table out of this class
public class UserClickData {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private String u_search_term;
private String u_sysid;
private String u_type;
#Transient
private long count;
public UserClickData(String u_type, long Count) { //, long count
this.u_type = u_type;
this.count=count;
}
public long getCount() {
return count;
}
public void setCount(long count) {
this.count=count;
}
public int getSys_id() {
return sys_id;
}
public void setSys_id(int sys_id) {
this.sys_id = sys_id;
}
public String getU_search_term() {
return u_search_term;
}
public void setU_search_term(String u_search_term) {
this.u_search_term = u_search_term;
}
public String getU_type() {
return u_type;
}
public void setU_type(String u_type) {
this.u_type = u_type;
}
}
Projection:
public interface UserClickProjection {
String getU_type();
long getCount();
}
DAO Code:
import java.util.List;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import com.abc.datacollection.entity.UserClickData;
import com.abc.datacollection.entity.UserClickProjection;
import com.abc.datacollection.entity.UserProjection;
public interface UserClickDataRepository extends CrudRepository<UserClickData, Integer> {
public static final String FIND_QUERY =
"select new com.abc.datacollection.entity.UserClickData(user.u_type, COUNT(u_type)) from UserClickData user GROUP BY user.u_type ORDER BY COUNT(user.u_type) DESC";
#Query(value = FIND_QUERY)
//public List<UserProjection> getAllRequestResponseRecords();
List<UserClickProjection> findAllProjectedBy();
}
Controller:
#CrossOrigin(origins = "*")
#GetMapping(path="/all")
public #ResponseBody List<UserClickProjection> getAllUserClickDataRecords() {
return userClickDataRepository.findAllProjectedBy();
}
Import javax.persistence.Transient instead of org.springframework.data.annotation.Transient
I have made a spring boot application connected to an angular front end. When the user enters a value into attendance id and hits submit on the form, this calls a method that updates the current value in the database using a HTTP PUT request.
However, the value is not being update despite break points showing the new value is being received and updated.
I am new to spring boot so any help is appreciated.
package com.example.demo.Attendance;
import javax.persistence.EmbeddedId;
import javax.persistence.Entity;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.transaction.Transactional;
import com.example.demo.AttendancePK.AttendancePK;
import com.example.demo.AttendanceType.AttendanceType;
import com.example.demo.LessonRun.LessonRun;
import com.fasterxml.jackson.annotation.JsonIgnore;
#Transactional
#Entity
public class Attendance {
#EmbeddedId
private AttendancePK id;
#ManyToOne
#JoinColumn(name="attendance_type", insertable = false, updatable=false)
private AttendanceType attendanceType;
#ManyToOne
#JsonIgnore
#JoinColumn(name="lesson_run_id", insertable = false, updatable=false)
private LessonRun lessonRun;
public LessonRun getLessonRun() {
return lessonRun;
}
public void setLessonRun(LessonRun lessonRun) {
this.lessonRun = lessonRun;
}
public AttendanceType getAttendanceType() {
return attendanceType;
}
public void setAttendanceType(AttendanceType attendanceType) {
this.attendanceType = attendanceType;
}
public Attendance(AttendancePK id, AttendanceType attendanceType, LessonRun lessonRun) {
super();
this.id = id;
this.attendanceType = attendanceType;
this.lessonRun = lessonRun;
}
public Attendance() {
}
public AttendancePK getId() {
return id;
}
public void setId(AttendancePK id) {
this.id = id;
}
}
My controller
#RequestMapping(value="/attendance/{attendanceId}/student/{studentId}/lessonrun/{lessonRunId}",method = RequestMethod.PUT)
public void updateAttendance(#PathVariable int attendanceId, #PathVariable int studentId, #PathVariable int lessonRunId, #RequestBody int attendanceTypeId) {
AttendancePK id = new AttendancePK(attendanceId, studentId,lessonRunId);
Attendance attendanceInDB = attendanceService.getAttendancebyId(id);
// attendanceInDB.setAttendanceType(int.getAttendanceType());
attendanceService.updateAttendance(attendanceInDB, attendanceTypeId);
}
My Service
package com.example.demo.Attendance;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.example.demo.AttendancePK.AttendancePK;
import com.example.demo.AttendanceType.AttendanceType;
import com.example.demo.AttendanceType.AttendanceTypeRepository;
#Service
public class AttendanceService {
#Autowired
private AttendanceRepository attendanceRepository;
#Autowired
private AttendanceTypeRepository attendanceTypeRepository;
public List<Attendance> getAllAttendanceRecs() {
List<Attendance> attendanceList = new ArrayList<>();
attendanceRepository.findAll().forEach(attendanceList::add);
return attendanceList;
}
public Attendance getAttendancebyId(AttendancePK id) {
Optional<Attendance> optionalAttendance = attendanceRepository.findById(id);
if (optionalAttendance.isPresent()) {
return optionalAttendance.get();
}
return null;
}
public void updateAttendance(Attendance attendanceInDB, int attendanceTypeId) {
Optional<AttendanceType> attendanceType = attendanceTypeRepository.findById(attendanceTypeId);
if (attendanceType.isPresent()) {
attendanceInDB.setAttendanceType(attendanceType.get());
attendanceRepository.save(attendanceInDB);
}
}
}
the breakpoint results show the value is updated shown here
but MySQL database doesn't reflect this