Android Room Database: stmt.bindLong(1, value.ID); - java

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

Related

repository.save function changes id of it's children entity

I'm trying to update existing entry in parent Entity and I encounter error I can't understand nor resolve.
I have two entities in a simple crud repository - Parent(User) and Children(movie). I am trying to pass a favourite movie to an user. The goal is that the movie doesn't have to be already in database, and the #PostMapping has to accept an user_id and movie name as parameters, other method uses the movie name, goes through the OMDBapi, parses data from json to fields and then gives the user at user_id the movie as a favourite. The PostMapping sort of works, because it gets the user at user_id, the movie is also added, but when the url looks like this - http://localhost:8080/users/2/fight+club the user at user_id 2 gets the movie as his favourite, but the movie gets it's id also as 2, even if it's first movie being added to repository. What I don't understand is why when I try to debug this every line of code is acting as I expect it to do -
wUser(id=2, name=Jan, favouriteMovies=[Movie(id=1, title=Fight Club, plot=An insomniac office worker and a devil-may-care soap maker form an underground fight club that evolves into much more., genre=Drama, director=David Fincher, posterURL=https://m.media-amazon.com/images/M/MV5BNDIzNDU0YzEtYzE5Ni00ZjlkLTk5ZjgtNjM3NWE4YzA3Nzk3XkEyXkFqcGdeQXVyMjUzOTY1NTc#._V1_SX300.jpg)])
but after it passes repository.save(user) line I get redirected to InvocableHandlerMethod class, into doInvoke method, into
return KotlinDetector.isSuspendingFunction(method) ? this.invokeSuspendingFunction(method, this.getBean(), args) : method.invoke(this.getBean(), args);
this line, and after that it's just deep into the rabbit hole. As I am quite an inexperienced in coding in Java, what probably can be deducted, I don't really understand nor can find solution to this problem.
The entities and controller classes below
package com.example.omdbapirest.movie;
import jakarta.persistence.*;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
#Entity
#Data
#AllArgsConstructor
#NoArgsConstructor
public class Movie {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name="movie_id")
private Integer id;
private String title;
private String plot;
private String genre;
private String director;
private String posterURL;
public Movie(String title, String plot, String genre, String director, String posterURL) {
this.title = title;
this.plot = plot;
this.genre = genre;
this.director = director;
this.posterURL = posterURL;
}
}
package com.example.omdbapirest.user;
import com.example.omdbapirest.movie.Movie;
import jakarta.persistence.*;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.List;
#Data
#Entity
#NoArgsConstructor
#AllArgsConstructor
public class wUser {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private String name;
// #OneToMany(cascade = {CascadeType.MERGE, CascadeType.PERSIST, CascadeType.DETACH})
#OneToMany(cascade =CascadeType.ALL)
#JoinColumn(name = "movie_id")
private List<Movie> favouriteMovies;
public wUser(String name) {
this.name = name;
}
}
UserController
package com.example.omdbapirest.user;
import com.example.omdbapirest.movie.Movie;
import com.example.omdbapirest.movie.MovieService;
import lombok.RequiredArgsConstructor;
import org.json.simple.parser.ParseException;
import org.springframework.web.bind.annotation.*;
import java.util.ArrayList;
import java.util.List;
#RestController
#RequestMapping("/users")
#RequiredArgsConstructor
public class UserController {
private final MovieService movieService;
private final UserRepository repository;
private final UserService service;
#GetMapping
public List<wUser> getUsers(){
return repository.findAll();
}
#PostMapping("/{id}/{moviename}")
public void addMovieAsFavorite (#PathVariable (name= "id") int id,
#PathVariable (name="moviename") String moviename)
throws ParseException{
String url = "https://www.omdbapi.com/?t="+moviename+"&apikey=30ccf40c";
wUser user = repository.getById(id);
List<Movie> movies = user.getFavouriteMovies();
List<Movie>moviesToAdd = new ArrayList<>();
Movie movie = movieService.getDataFromOMDBAsMovie(url);
movies.add(movie);
moviesToAdd.addAll(movies);
user.setFavouriteMovies(moviesToAdd);
repository.save(user);
}
}
I'm also adding MovieService class in case there is some error in the JSON parser
package com.example.omdbapirest.movie;
import lombok.RequiredArgsConstructor;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import org.springframework.stereotype.Service;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.List;
#Service
#RequiredArgsConstructor
public class MovieService {
private final MovieRepository repository;
public String getJSONFromURL(String strUrl) {
String jsonText = "";
try {
URL url = new URL(strUrl);
InputStream is = url.openStream();
BufferedReader bufferedReader =
new BufferedReader(new InputStreamReader(is));
String line;
while ((line = bufferedReader.readLine()) != null) {
jsonText += line + "\n";
}
is.close();
bufferedReader.close();
} catch (Exception e) {
e.printStackTrace();
}
return jsonText;
}
public Movie getDataFromOMDBAsMovie(String strURL) throws ParseException {
String json = getJSONFromURL(strURL);
Movie movie = new Movie();
JSONParser parser = new JSONParser();
Object object = parser.parse(json);
JSONObject mainJsonObject = (JSONObject) object;
String title = (String)mainJsonObject.get("Title");
movie.setTitle(title);
String plot = (String)mainJsonObject.get("Plot");
movie.setPlot(plot);
String genre = (String)mainJsonObject.get("Genre");
movie.setGenre(genre);
String director = (String)mainJsonObject.get("Director");
movie.setDirector(director);
String posterURL = (String)mainJsonObject.get("Poster");
movie.setPosterURL(posterURL);
repository.save(movie);
return movie;
}
public Movie addMovie(Movie movie){
return repository.save(movie);
}
}
I tried adding movies to db, reworking the favourite saving class, all to no avail, I was getting different errors when not debuging, including
org.h2.jdbc.JdbcSQLIntegrityConstraintViolationException: Pole nie może być NULL"MOVIE_ID"(Field cannot be NULL)
NULL not allowed for column "MOVIE_ID"; SQL statement:
update movie set movie_id=null where movie_id=? [23502-214]
and
org.h2.jdbc.JdbcSQLIntegrityConstraintViolationException: Naruszenie ograniczenia Klucza Głównego lub Indeksu Unikalnego: "PRIMARY KEY ON PUBLIC.MOVIE(MOVIE_ID)(translating to- Unique Index or primary key violated)
( /* key:2 */ 2, 'David Fincher', 'Drama', 'An insomniac office worker and a devil-may-care soap maker form an underground fight club that evolves into much more.', 'https://m.media-amazon.com/images/M/MV5BNDIzNDU0YzEtYzE5Ni00ZjlkLTk5ZjgtNjM3NWE4YzA3Nzk3XkEyXkFqcGdeQXVyMjUzOTY1NTc#._V1_SX300.jpg', 'Fight Club')"
Unique index or primary key violation: "PRIMARY KEY ON PUBLIC.MOVIE(MOVIE_ID) ( /* key:2 */ 2, 'David Fincher', 'Drama', 'An insomniac office worker and a devil-may-care soap maker form an underground fight club that evolves into much more.', 'https://m.media-amazon.com/images/M/MV5BNDIzNDU0YzEtYzE5Ni00ZjlkLTk5ZjgtNjM3NWE4YzA3Nzk3XkEyXkFqcGdeQXVyMjUzOTY1NTc#._V1_SX300.jpg', 'Fight Club')"; SQL statement:
insert into movie (director, genre, plot, posterurl, title, movie_id) values (?, ?, ?, ?, ?, ?) [23505-214]
Both of these errors appear when I try to add another movie to given user, I mean I was able to give all users 1 movie, but never more since it tries to always add the movie with id of the user
Let's focus on the relevant part of your mapping:
public class Movie {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name="movie_id")
private Integer id;
}
and
public class wUser {
#OneToMany(cascade =CascadeType.ALL)
#JoinColumn(name = "movie_id")
private List<Movie> favouriteMovies;
}
The id property of Movie is mapped to the table column movie_id by the configuration in the Movie class.
But for the wUser.favouriteMovies you use #JoinColumn to make it use movie_id the join column, i.e. the column in the Movie table that references the wUser.
By this that column is mapped to two completely different values and it seems in your scenario the second one wins.
To fix this simply choose a different column for the join column. user_id might be a good choice.

GraphQL returning null when queried

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

Create a Table with Rows in Android Room

I am making an Android app that has a database. I am able to create all the tables I need but need to populate some tables with static data. I tried doing this with a migration but cannot get the code to run as I expect. This data is needed for that app to run and will not change. Is a migration that runs immediately after the database is created the correct way to do this? I want to be sure that the rows only get created once and the app will never need to check for their existence after the database is created.
All the relevant classes are below. Let me know if any more details are needed. TIA!
Status
import androidx.annotation.NonNull;
import androidx.room.Entity;
import androidx.room.Index;
import androidx.room.PrimaryKey;
#Entity(tableName = "Status", indices = { #Index(value = {"Name"}, unique = true) })
public class Status
{
#PrimaryKey(autoGenerate = true)
public int Id;
#NonNull
public String Name;
}
StatusEnum
public enum StatusEnum
{
New(1, "New"),
InProgress(2, "In Progress"),
Closed(3, "Closed");
public final int Id;
public final String Name;
StatusEnum(int id, String name)
{
Id = id;
Name = name;
}
}
StaticDataMigration
import static androidx.test.core.app.ApplicationProvider.getApplicationContext;
import android.os.Build;
import androidx.annotation.RequiresApi;
import androidx.room.Database;
import androidx.room.Room;
import androidx.room.RoomDatabase;
import androidx.room.migration.Migration;
import androidx.sqlite.db.SupportSQLiteDatabase;
#RequiresApi(api = Build.VERSION_CODES.O)
#Database(entities = { Status.class }, version = 2, exportSchema = false)
public abstract class StaticDataMigration extends RoomDatabase
{
public static final Migration MIGRATION_1_2 = new Migration(1, 2)
{
#Override
public void migrate(SupportSQLiteDatabase database)
{
sql = "INSERT INTO Status VALUES ";
for (StatusEnum enumType : StatusEnum.values())
{
sql = sql + String.format("(%d, %s),", enumType.Id, enumType.Name);
}
sql = removeLastChar(SQL);
database.beginTransaction();
database.execSQL(sql);
database.endTransaction();
Room.databaseBuilder(getApplicationContext(), MyDatabase.class, "MyDatabase").addMigrations(MIGRATION_1_2).build();
}
//Room.databaseBuilder(Context, MyDatabase.class, "MyDatabase").addMigrations(MIGRATION_1_2).build();
//Database.mig(Context, MyDatabase., "MyDatabase").addMigrations(MIGRATION_1_2).build();
};
private static String removeLastChar(String s)
{
return (s == null || s.length() == 0) ? null : (s.substring(0, s.length() - 1));
}
}

Android Room Database: How to properly select a 'tableName' in the DAO #Query?

I've been trying to select the tableName set in the #Entity annotation within the #Query method in the Dao interface, but it won't recognize tableName and id. Am I missing something?
Cannot resolve symbol 'photo_table'
Cannot resolve symbol 'id'
//Entity file
import androidx.room.Entity;
import androidx.room.PrimaryKey;
#Entity(tableName = "photo_table")
public class Photo {
#PrimaryKey(autoGenerate = true)
public int id;
public int photoItem;
public String title;
public String description;
}
// Dao Interface
import androidx.room.Dao;
import androidx.room.Delete;
import androidx.room.Insert;
import androidx.room.Query;
import androidx.room.Update;
import androidx.lifecycle.LiveData;
import java.util.List;
#Dao
public interface PhotoDao {
#Insert
void Insert(Photo photo);
#Update
void Update(Photo photo);
#Delete
void Delete(Photo photo);
#Query("SELECT * FROM photo_table ORDER BY id ASC")
LiveData<List<Photo>> getAllPhotos();
}
You might have forgotten add your entity class to required annotation in your abstract class extends RoomDatabase.
#Database(entities = {Photo.class}, version = 1)
abstract class AppDatabase extends RoomDatabase {
...
}

Error while displaying COUNT(variable) in CrudRepository using SQL query

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

Categories

Resources