So Basically, I'm currently having a problem with my program, where I would like to create an array list of objects and have the values placed by the user, I've yet to go about how to doing that.
In my main class, I've created these attributes.
List<Games> games = new ArrayList<Games>();
List<Company> company = new ArrayList<Company>();
int userchoice;
And in the games.java class I used similar attributes for receiving data.
games.java
public List<Games> getTitles() {
return titles;
}
public void setTitles(List<Games> titles) {
this.titles = titles;
}
I would use games.add(gameTitle); to place values, but it would give me 2 errors.
One of them would tell me that incompatible types: String cannot be converted into Games when I use the games.add(1, gamesTitle);
The next would tell me
method collection.Add(Games) is not applicable, String cannot be converted to Games.
What I'm trying to do is to get the user values from gameID and game Title, into an arrayList that will then send that data to classes as arguments and place them into a database.
This is a Java Persistence API project I'm working on and any help would be appreciated. Thank you
Games.java Class
#Entity (name = "Games")
public class Games implements Serializable {
#Id
private int id;
private String title;
private String genre;
#ManyToOne
#JoinColumn(name="GamesComp")
private Company comp_Name;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getGenre() {
return genre;
}
public void setGenre(String genre) {
this.genre = genre;
}
public Company getComp_Name() {
return comp_Name;
}
public void setComp_Name(Company comp_Name) {
this.comp_Name = comp_Name;
}
#Override
public String toString() {
return "Game ID: " + getId() + " Title: " + getTitle() +
" with " + getGenre();
}
Company Class
#Entity
#Table (name="Company")
public class Company implements Serializable {
#Id
private int id;
private String compName;
#OneToMany(cascade = ALL, mappedBy="comp")
private List<Games> titles;
public Company() {
titles = new ArrayList<>();
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getCompName() {
return compName;
}
public void setCompName(String compName) {
this.compName = compName;
}
public void addGameTitles(Games t) {
this.titles.add(t);
t.setComp_Name(this);
}
public List<Games> getTitles() {
return titles;
}
public void setTitles(List<Games> titles) {
this.titles = titles;
}
#Override
public String toString() {
return "Company ID: " + getId() +
", Company Name: " + getCompName();
}
The issue is: you are trying to insert an string object into a List of Games Objects...
replace this List<Games> games = new ArrayList<Games>();
for this:
List<String> games = new ArrayList<String>();
you could of course define the Games Class like
class Games{
...
Games(String gameTitle){
}
and some where in the code add games to the list of games:
games.add(new Games("CallOfDuty"));
imho, the last option is more elegant and reflects a better design model..
but you have the freedom of choice.
Related
I am currently building an android app, which displays a Route, which is constructed out of multiple waypoints. I already planned the database schema (chen-notation [possibly invalid "syntax"]):
I tried to recreate the n-m relation with android room, but I can't figure out how I can retrieve the index_of_route attribute of the junction table (route_waypoint).
I want the junction table attribute index_of_route, when I get the Data like so:
#Transaction
#Query("SELECT * FROM POIRoute")
List<RouteWithWaypoints> getRoutes();
inside the POIWaypoint class (maybe as extra attribute), or at least accessible from another class which maybe is implemented like so:
#Embedded
POIWaypoint waypoint;
int indexOfRoute;
Currently I don't get the indexOfRoute attribute from the junction table.
My already created classes:
RouteWithWaypoints:
public class RouteWithWaypoints {
#Embedded
private POIRoute poiRoute;
#Relation(parentColumn = "id",entityColumn = "id",associateBy = #Junction(value = RouteWaypoint.class, parentColumn = "routeId", entityColumn = "waypointId"))
private List<POIWaypoint> waypoints;
public POIRoute getPoiRoute() {
return poiRoute;
}
public void setPoiRoute(POIRoute poiRoute) {
this.poiRoute = poiRoute;
}
public List<POIWaypoint> getWaypoints() {
return waypoints;
}
public void setWaypoints(List<POIWaypoint> waypoints) {
this.waypoints = waypoints;
}
RouteWaypoint:
#Entity(primaryKeys = {"waypointId", "routeId"}, foreignKeys = {
#ForeignKey(entity = POIWaypoint.class, parentColumns = {"id"}, childColumns = {"waypointId"}),
#ForeignKey(entity = POIRoute.class, parentColumns = {"id"}, childColumns = {"routeId"})
})
public class RouteWaypoint {
private int waypointId;
private int routeId;
// I want this attribute inside the POIWaypoint class
#ColumnInfo(name = "index_of_route")
private int indexOfRoute;
public int getWaypointId() {
return waypointId;
}
public void setWaypointId(int waypointId) {
this.waypointId = waypointId;
}
public int getRouteId() {
return routeId;
}
public void setRouteId(int routeId) {
this.routeId = routeId;
}
}
POIRoute:
#Entity
public class POIRoute{
private String name;
private String description;
#PrimaryKey(autoGenerate = true)
private int id;
private boolean user_generated;
private int parentId;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public boolean isUser_generated() {
return user_generated;
}
public void setUser_generated(boolean user_generated) {
this.user_generated = user_generated;
}
public int getParentId() {
return parentId;
}
public void setParentId(int parentId) {
this.parentId = parentId;
}
}
POIWaypoint (please ignore the position attribute it isn't finished):
#Entity
public class POIWaypoint {
#PrimaryKey(autoGenerate = true)
private long id;
#ColumnInfo(name = "long_description")
private String longDescription;
private String title;
#ColumnInfo(name = "short_description")
private String shortDescription;
// use converter: https://developer.android.com/training/data-storage/room/referencing-data
#Ignore
private GeoPoint position;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public GeoPoint getPosition() {
return position;
}
public void setPosition(GeoPoint position) {
this.position = position;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getShortDescription() {
return shortDescription;
}
public void setShortDescription(String shortDescription) {
this.shortDescription = shortDescription;
}
public String getLongDescription() {
return longDescription;
}
public void setLongDescription(String longDescription) {
this.longDescription = longDescription;
}
I solved my problem by manage the relation by myself. I changed my RouteDao to an abstract class to insert my own method, which manages part of the junction table by itself:
RouteDao:
private RouteDatabase database;
public RouteDao(RouteDatabase database) {
this.database = database;
}
#Query("Select * from POIRoute")
public abstract List<POIRoute> getRoutes();
#Query("SELECT * FROM POIRoute WHERE id = :id")
public abstract POIRoute getRoute(int id);
#Insert
abstract void insertRouteWithWaypoints(RouteWithWaypoints routeWithWaypoints);
public List<RouteWithWaypoints> getRoutesWithWaypoints() {
List<POIRoute> routes = this.getRoutes();
List<RouteWithWaypoints> routesWithWaypoints = new LinkedList<>();
for (POIRoute r : routes) {
routesWithWaypoints.add(new RouteWithWaypoints(r, database.wayPointDao().getWaypointsFromRoute(r.getId())));
}
return routesWithWaypoints;
}
public RouteWithWaypoints getRouteWithWaypoints(int id) {
POIRoute route = this.getRoute(id);
RouteWithWaypoints routeWithWaypoints = null;
if (route != null) {
routeWithWaypoints = new RouteWithWaypoints(route, database.wayPointDao().getWaypointsFromRoute(route.getId()));
}
return routeWithWaypoints;
}
WayPointDao:
#Query("SELECT * FROM POIWaypoint")
POIWaypoint getWaypoints();
#Query("SELECT * FROM POIWaypoint WHERE id = :id")
POIWaypoint getWaypoint(long id);
#Query("SELECT pw.*, rw.index_of_route as 'index' FROM POIWaypoint as pw Join RouteWaypoint as rw on (rw.waypointId = pw.id) where rw.routeId = :id order by 'index' ASC")
List<POIRouteStep> getWaypointsFromRoute(int id);
I'm looking to persist some data classes. I've been investigating using Room for this, which is very straight forward to do if it's just a case of a stand alone data class. However the objects I am trying to persist are sub classes, which adds a layer of complexity.
THIS CODE HAS NOT BEEN COMPILED, WRITTEN IN SO FOR ILLUSTRATION PURPOSES ONLY
So with a simple straight forward class
#Entity(tableName = TABLE_NAME)
public class Event implements MyEvent {
public static final String TABLE_NAME = "events";
public static final String DATE_FIELD = "date";
#PrimaryKey(autoGenerate = true)
private int id;
private String name;
private String description;
#ColumnInfo(name = DATE_FIELD)
private LocalDateTime date;
public Event(int id, String name, String description, LocalDateTime date) {
this.id = id;
this.name = name;
this.description = description;
this.date = date;
}
#Override
public int getId() {
return id;
}
#Override
public String getName() {
return name;
}
#Override
public String getDescription() {
return description;
}
#Override
public LocalDateTime getDate() {
return date;
}
#Override
public String toString() {
return "Event{" +
"id=" + id +
", name='" + name + '\'' +
", description='" + description + '\'' +
", date=" + date +
'}';
}
public long getDaysUntil() {
return ChronoUnit.DAYS.between(LocalDateTime.now(), getDate());
}
}
That's straight forward but if you have for example
public class MusicEvent extends Event implements MyEvents {
private String musicType;
private boolean supportActs;
#Override
public int getId() {
return id;
}
#Override
public String getName() {
return name;
}
#Override
public String getDescription() {
return description;
}
#Override
public LocalDateTime getDate() {
return date;
}
public void setMusicType(String musicType) {
this.musicType = musicType;
}
public String getMusicType() {
return this.musicType;
}
public void setSupportActs(boolean supportActs) {
this.supportActs = supportActs;
}
public boolean getSupportActs() {
return this.supportActs;
}
}
public interface MyEvents {
int getId();
String getName();
String getDescription();
LocalDate getDate();
}
So what I want to do is have one table of events, I don't want to have multiple tables for e.g. music events, film events, drama events.
Or if they all implement MyEvents they can all be type MyEvents.
I would like to be able to persist all Event objects and when required retrieve all event objects.
If anyone could share some info on this I'd greatly appreciate it.
In my Spring boot application, I have collection of Todos and a collection of Courses. In the view of the application, I return the collection of courses and display whatever course I need. The Todos are stored as 1 list which represents all the current Todos. What I would like to do is return a list of Todos for each course. So when the view is opened, the application would display the the course plus the individual todo list for that course.
Is there a way I can use the existing code to incorporate the new functionality. I have created the front end logic and would like to keep that. My initial idea was to add the the course id to the Todo.java, but that did not work.
Todo.java
#Document(collection="todos")
public class Todo {
#Id
private String id;
#NotBlank
#Size(max=250)
#Indexed(unique=true)
private String title;
private Boolean completed = false;
private Date createdAt = new Date();
public Todo() {
super();
}
public Todo(String title) {
this.title = title;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public Boolean getCompleted() {
return completed;
}
public void setCompleted(Boolean completed) {
this.completed = completed;
}
public Date getCreatedAt() {
return createdAt;
}
public void setCreatedAt(Date createdAt) {
this.createdAt = createdAt;
}
#Override
public String toString() {
return String.format(
"Todo[id=%s, title='%s', completed='%s']",
id, title, completed);
}
}
TodoRepository.java
#Repository
public interface TodoRepository extends MongoRepository<Todo, String> {
public List<Todo> findAll();
public Todo findOne(String id);
public Todo save(Todo todo);
public void delete(Todo todo);
}
Courses
#Document(collection = "courses")
public class Courses {
#Id
private String id;
private String name;
private String lecturer;
private String picture;
private String video;
private String description;
private String enroled;
public Courses(){}
public Courses(String name, String lecturer, String picture, String video, String description,String enroled) {
this.name = name;
this.lecturer = lecturer;
this.picture = picture;
this.video = video;
this.description = description;
this.enroled = enroled;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getLecturer() {
return lecturer;
}
public void setLecturer(String lecturer) {
this.lecturer = lecturer;
}
public String getPicture() {
return picture;
}
public void setPicture(String picture) {
this.picture = picture;
}
public String getVideo() {
return video;
}
public void setVideo(String video) {
this.video = video;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getEnroled() {
return enroled;
}
public void setEnroled(String enroled) {
this.enroled = enroled;
}
#Override
public String toString() {
return "Courses{" +
"id='" + id + "'" +
", name='" + name + "'" +
", lecturer='" + lecturer + "'" +
", description='" + description + "'" +
'}';
}
}
My goal :
In Spring MVC I have to save mobile phone contact list into database.
example:
phone1 sonia 2554654 work
2554654 home
multiple phone_number with multiple phone_Number type
contacts table
id,
contact_name
phone_number
phone_type
in my java class I have
public class ContactMobile {
private String type;
private String number;
public ContactMobile() {
}
public ContactMobile(String type, String number) {
super();
this.type = type;
this.number = number;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getNumber() {
return number;
}
public void setNumber(String number) {
this.number = number;
}
}
and here I use SET for phone number and type
#Entity
#Table(name = "_contact")
public class MobileContact {
private String id;
private String fullname;
private Set<ContactMobile> mobileNumbers;
public MobileContact(String fullname, Set<ContactMobile> mobileNumbers) {
super();
this.fullname = fullname;
this.mobileNumbers = mobileNumbers;
}
#Id
#Column(name = "Id")
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
#Column(name = "fullname")
public String getFullname() {
return fullname;
}
public void setFullname(String fullname) {
this.fullname = fullname;
}
public Set<ContactMobile> getMobileNumbers() {
return mobileNumbers;
}
public void setMobileNumbers(Set<ContactMobile> mobileNumbers) {
this.mobileNumbers = mobileNumbers;
}
public MobileContact() {
super();
}
}
I am using hibernate to store data..
my question is in my MobileContact class in
public Set<ContactMobile> getMobileNumbers() {
return mobileNumbers;
}
what annotation I have to use here to save multiple phonenumbers?
The MobileContact entity has many ContactMobile, it is a OneToMany relation. In your ContactMobile table, you should has a field for the id of MobileContact, like mobile_contact_id, and set the join column on that field as below in your ContactMobile:
#OneToMany(fetch = FetchType.LEZY)
#JoinColumn(name = "mobile_contact_id")
private Set<ContactMobile> mobileNumbers;
You can get the detail about the relation in this.
You can use the Embeddables (instead of Entities) for very simple value objects like MobileContact (then they do not need an ID, and the are no just simple value objects without own identity)
#Embeddable
public class ContactMobile {...
//implement an equals and hashcode method!
}
public class MobileContact {
...
#ElementCollection
private Set<ContactMobile> mobileNumbers;
...
}
#See Java Persistence/ElementCollection
Trying to figure out how to use hibernate to call to get a list of the movies for a given genre?!
I tried getting a given genre then using the method from GenreDTO to get the set of movies.
Query hqlQuery = session.createQuery("FROM GenreDTO WHERE genre like :genre");
GenreDTO g = hqlQuery.setParameter("title","%" + term + "%").uniqueResult();
return g.getMovies();
Is there a better way?
CREATE TABLE Movie (
id INTEGER PRIMARY KEY NOT NULL GENERATED ALWAYS AS IDENTITY (START WITH 1, INCREMENT BY 1),
title VARCHAR(255),
poster VARCHAR(255),
director VARCHAR(255),
actors VARCHAR(255),
synopsis VARCHAR(3000),
release_date TIMESTAMP
);
CREATE TABLE Genre(
id INTEGER PRIMARY KEY NOT NULL GENERATED ALWAYS AS IDENTITY (START WITH 1, INCREMENT BY 1),
genre VARCHAR(255)
);
CREATE TABLE MovieHasGenre(
movie_id INTEGER REFERENCES Movie (id) NOT NULL,
genre_id INTEGER REFERENCES Genre (id) NOT NULL,
PRIMARY KEY (movie_id, genre_id)
);
package edu.unsw.comp9321.jdbc;
import java.util.HashSet;
import java.util.Set;
public class GenreDTO {
public GenreDTO() {}
public GenreDTO(int id, String genre) {
super();
this.id = id;
this.genre = genre;
}
private int id;
private String genre;
private Set<MovieDTO> movies = new HashSet<MovieDTO>();
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getGenre() {
return genre;
}
public void setGenre(String genre) {
this.genre = genre;
}
public Set<MovieDTO> getMovies() {
return movies;
}
public void setMovies(Set<MovieDTO> movies) {
this.movies = movies;
}
}
package edu.unsw.comp9321.jdbc;
import java.util.Comparator;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.OneToMany;
public class MovieDTO implements Comparable {
private int id;
private String title;
private String poster;
private String director;
private String actors;
private String synopsis;
private String release_date;
private int cinema_id;
private Set<GenreDTO> genres = new HashSet<GenreDTO>();
private Set<ReviewDTO> reviews = new HashSet<ReviewDTO>();
private double rating;
public MovieDTO() {
}
public MovieDTO(int id, String title, String poster, String director,
String actors, String synopsis, String release_date, double rating) {
super();
this.id = id;
this.title = title;
this.poster = poster;
this.director = director;
this.actors = actors;
this.synopsis = synopsis;
this.release_date = release_date;
this.rating = rating;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getPoster() {
return poster;
}
public void setPoster(String poster) {
this.poster = poster;
}
public String getDirector() {
return director;
}
public void setDirector(String director) {
this.director = director;
}
public String getActors() {
return actors;
}
public void setActors(String actors) {
this.actors = actors;
}
public String getSynopsis() {
return synopsis;
}
public void setSynopsis(String synopsis) {
this.synopsis = synopsis;
}
public String getRelease_date() {
return release_date;
}
public void setRelease_date(String release_date) {
this.release_date = release_date;
}
public Set<GenreDTO> getGenres() {
return genres;
}
public void setGenres(Set<GenreDTO> genres) {
this.genres = genres;
}
public Set<ReviewDTO> getReviews() {
return reviews;
}
public void setReviews(Set<ReviewDTO> reviews) {
this.reviews = reviews;
}
public int getCinema_id() {
return cinema_id;
}
public void setCinema_id(int cinema_id) {
this.cinema_id = cinema_id;
}
public double getRating() {
return rating;
}
public void setRating(double rating) {
this.rating = rating;
}
#Override
public int compareTo(Object o) {
MovieDTO other = (MovieDTO) o;
if (this.rating > other.rating) return -1;
if (this.rating < other.rating) return 1;
return 0;
}
}
Yes. There is a better way. Just use a join:
select m from Movie m join m.genres g where g.genre like :genre
or
select m from Genre g join g.movies m where g.genre like :genre
Note that using a like clause is a bit odd. You should use the ID of the genre to uniquely identify it. And if you only have part of a genre's name, you shouldn't assume only one genre contains this genre part.
Also, a DTO is not an entity, and vice-versa. Don't name an entity GenreDTO or MovieDTO. Name it Genre or Movie.