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.
Related
I have multiple Entities mapped to my MySQL database and I can map those entities into relevant objects using Spring's CrudRepository. The three entities are: Snapshot, Market, and Contract
Each Snapshot contains a unique id, a timestamp, and a List of Market objects
Each Market contains a unique primary key id, a nonUniquemarketId, name, url, ...., and List of Contract objects.
Each Contract contains fields regarding pricing information.
The nonUniqueMarketId is an id given by the API I am getting data from. It only occurs once in each Snapshot's List of Market objects
I am wondering if it is possible to get the List of Contracts from a specific Market in List of Markets from a specific Snapshot. That is, if I have a Snapshot's timestamp and a nonUniqueMarketId, is it possible to write a query that looks at all the Snapshots in the DB, gets the one with the given timestamp, then looks at that Snapshot's List of Markets and either gets that Market whose nonUniqueMarketId is given or the List of Contracts field in it?
More generally, I know what Snapshot I want and what Market I want, is it possible to get that specific Market given those two parameters?
Snapshot.java
package com.axlor.predictionassistantanalyzer.model;
import com.fasterxml.jackson.annotation.JsonProperty;
import javax.persistence.*;
import java.util.List;
#Entity
public class Snapshot{
#Id
private Integer hashId;
#JsonProperty("markets")
#ElementCollection(fetch=FetchType.EAGER)
#OneToMany(cascade=CascadeType.ALL, fetch=FetchType.EAGER) //ALL, not persist
private List<Market> markets;
private long timestamp;
public Snapshot(List<Market> markets, long timestamp, Integer hashId) {
this.markets = markets;
this.timestamp = timestamp;
this.hashId = hashId;
}
public Snapshot() {
}
public void setMarkets(List<Market> markets){
this.markets = markets;
}
public List<Market> getMarkets(){
return markets;
}
public long getTimestamp() {
return timestamp;
}
public void setTimestamp(long timestamp) {
this.timestamp = timestamp;
}
public Integer getHashId() {
return hashId;
}
public void setHashId(Integer hashId) {
this.hashId = hashId;
}
#Override
public String toString() {
return "Snapshot{" +
"hashId=" + hashId +
", markets=" + markets +
", timestamp=" + timestamp +
'}';
}
}
Market.java
package com.axlor.predictionassistantanalyzer.model;
import com.fasterxml.jackson.annotation.JsonProperty;
import javax.persistence.*;
import java.util.List;
#Entity
public class Market {
#Id
#GeneratedValue
private Integer marketUniqueID;
#JsonProperty("timeStamp")
private String timeStamp;
#Transient
#JsonProperty("image")
private String image;
#JsonProperty("name")
private String name;
#JsonProperty("id")
private int id;
#Transient
#JsonProperty("shortName")
private String shortName;
#ElementCollection(fetch=FetchType.EAGER)
#OneToMany(cascade=CascadeType.ALL, fetch=FetchType.EAGER) //ALL, not persist
#JsonProperty("contracts")
private List<Contract> contracts;
#JsonProperty("url")
private String url;
#JsonProperty("status")
private String status;
public Market(String timeStamp, String image, String name, int id, String shortName, List<Contract> contracts, String url, String status) {
this.timeStamp = timeStamp;
this.image = image;
this.name = name;
this.id = id;
this.shortName = shortName;
this.contracts = contracts;
this.url = url;
this.status = status;
}
public Market() {
}
public Integer getMarketUniqueID() {
return marketUniqueID;
}
public void setMarketUniqueID(Integer marketUniqueID) {
this.marketUniqueID = marketUniqueID;
}
public String getTimeStamp() {
return timeStamp;
}
public void setTimeStamp(String timeStamp) {
this.timeStamp = timeStamp;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getShortName() {
return shortName;
}
public void setShortName(String shortName) {
this.shortName = shortName;
}
public List<Contract> getContracts() {
return contracts;
}
public void setContracts(List<Contract> contracts) {
this.contracts = contracts;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
#Override
public String toString() {
return "\n\nMarket{" +
"marketUniqueID='" + marketUniqueID + '\'' +
", timeStamp='" + timeStamp + '\'' +
", image='" + image + '\'' +
", name='" + name + '\'' +
", id=" + id +
", shortName='" + shortName + '\'' +
", contracts=" + contracts +
", url='" + url + '\'' +
", status='" + status + '\'' +
"\n}";
}
}
Contract.java
package com.axlor.predictionassistantanalyzer.model;
import com.fasterxml.jackson.annotation.JsonProperty;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Transient;
#Entity
public class Contract {
/*
Why do we need contractUniqueID?:
See explanation in Market.java
Basically, the JsonProperty 'id' field cannot be used as a primary key in the database. We need to create one, so we generate it here.
*/
#Id
#GeneratedValue
private Integer contractUniqueID;
#Transient
#JsonProperty("image")
private String image;
#JsonProperty("lastClosePrice")
private double lastClosePrice;
#JsonProperty("bestBuyNoCost")
private double bestBuyNoCost;
#JsonProperty("bestSellNoCost")
private double bestSellNoCost;
#Transient
#JsonProperty("displayOrder")
private int displayOrder; //not sure what this even is supposed to do lol
#JsonProperty("dateEnd")
private String dateEnd;
#JsonProperty("bestSellYesCost")
private double bestSellYesCost;
#JsonProperty("bestBuyYesCost")
private double bestBuyYesCost;
#JsonProperty("lastTradePrice")
private double lastTradePrice;
#JsonProperty("name")
private String name;
#JsonProperty("id")
private int id;
#Transient
#JsonProperty("shortName")
private String shortName;
#JsonProperty("status")
private String status;
public Contract(String image, double lastClosePrice, double bestBuyNoCost, double bestSellNoCost, int displayOrder, String dateEnd, double bestSellYesCost, double bestBuyYesCost, double lastTradePrice, String name, int id, String shortName, String status) {
this.image = image;
this.lastClosePrice = lastClosePrice;
this.bestBuyNoCost = bestBuyNoCost;
this.bestSellNoCost = bestSellNoCost;
this.displayOrder = displayOrder;
this.dateEnd = dateEnd;
this.bestSellYesCost = bestSellYesCost;
this.bestBuyYesCost = bestBuyYesCost;
this.lastTradePrice = lastTradePrice;
this.name = name;
this.id = id;
this.shortName = shortName;
this.status = status;
}
public Contract() {
}
public Integer getContractUniqueID() {
return contractUniqueID;
}
public void setContractUniqueID(Integer contractUniqueID) {
this.contractUniqueID = contractUniqueID;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public double getLastClosePrice() {
return lastClosePrice;
}
public void setLastClosePrice(double lastClosePrice) {
this.lastClosePrice = lastClosePrice;
}
public double getBestBuyNoCost() {
return bestBuyNoCost;
}
public void setBestBuyNoCost(double bestBuyNoCost) {
this.bestBuyNoCost = bestBuyNoCost;
}
public double getBestSellNoCost() {
return bestSellNoCost;
}
public void setBestSellNoCost(double bestSellNoCost) {
this.bestSellNoCost = bestSellNoCost;
}
public int getDisplayOrder() {
return displayOrder;
}
public void setDisplayOrder(int displayOrder) {
this.displayOrder = displayOrder;
}
public String getDateEnd() {
return dateEnd;
}
public void setDateEnd(String dateEnd) {
this.dateEnd = dateEnd;
}
public double getBestSellYesCost() {
return bestSellYesCost;
}
public void setBestSellYesCost(double bestSellYesCost) {
this.bestSellYesCost = bestSellYesCost;
}
public double getBestBuyYesCost() {
return bestBuyYesCost;
}
public void setBestBuyYesCost(double bestBuyYesCost) {
this.bestBuyYesCost = bestBuyYesCost;
}
public double getLastTradePrice() {
return lastTradePrice;
}
public void setLastTradePrice(double lastTradePrice) {
this.lastTradePrice = lastTradePrice;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getShortName() {
return shortName;
}
public void setShortName(String shortName) {
this.shortName = shortName;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
#Override
public String toString() {
return "Contract{" +
"contractUniqueID='" + contractUniqueID + '\'' +
", image='" + image + '\'' +
", lastClosePrice=" + lastClosePrice +
", bestBuyNoCost=" + bestBuyNoCost +
", bestSellNoCost=" + bestSellNoCost +
", displayOrder=" + displayOrder +
", dateEnd='" + dateEnd + '\'' +
", bestSellYesCost=" + bestSellYesCost +
", bestBuyYesCost=" + bestBuyYesCost +
", lastTradePrice=" + lastTradePrice +
", name='" + name + '\'' +
", id=" + id +
", shortName='" + shortName + '\'' +
", status='" + status + '\'' +
'}';
}
}
I am using SQLite to store my information. I am storing the date as string format. Now I want to fetch the data based on the date, there might be more than one data for a single date. I have checked relevant questions and tried in my way but can not find the solution. Though I was able to get info of a single data for a particular date.
My code for fetching data from the database:
public ArrayList<ExpenseModel> getSingleExpenseDetails(String date){
SQLiteDatabase sqLiteDatabase=this.getReadableDatabase();
String query = "select * from " + TABLE_SAVE_EXPENSE + " where "+ COLUMN_EXPENSE_DATE+ " = '" + date+ "'";
Cursor cursor=sqLiteDatabase.rawQuery(query, null);
ExpenseModel expenseModel=new ExpenseModel();
ArrayList<ExpenseModel> expenseModels = new ArrayList<>();
Log.v("Title : ",""+title);
if (cursor.moveToFirst()){
do {
expenseModel.setTitle(cursor.getString(cursor.getColumnIndex(COLUMN_EXPENSE_TITLE)));
expenseModel.setDescription(cursor.getString(cursor.getColumnIndex(COLUMN_EXPENSE_DESCRIPTION)));
expenseModel.setAmount(cursor.getInt(cursor.getColumnIndex(COLUMN_EXPENSE_AMOUNT)));
expenseModel.setDate(cursor.getString(cursor.getColumnIndex(COLUMN_EXPENSE_DATE)));
expenseModel.setCurrency(cursor.getString(cursor.getColumnIndex(COLUMN_EXPENSE_CURRENCY)));
Log.v("Info : ",""+cursor.getString(cursor.getColumnIndex(COLUMN_EXPENSE_TITLE)));
expenseModels.add(expenseModel)
}while (cursor.moveToNext());
}
cursor.close();
sqLiteDatabase.close();
return expenseModels;
}
ExpenseModel class:
package app.shakil.com.dailyexpense.Models;
public class ExpenseModel {
private int id;
private String title;
private String description;
private String date;
private int amount;
private String currency;
public ExpenseModel(){
}
public ExpenseModel(String title,String description,String date,int amount,String currency){
this.title=title;
this.description=description;
this.date=date;
this.amount=amount;
this.currency=currency;
}
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 getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public int getAmount() {
return amount;
}
public void setAmount(int amount) {
this.amount = amount;
}
public String getCurrency() {
return currency;
}
public void setCurrency(String currency) {
this.currency = currency;
}
}
One obvious mistake that you do in your code is that you initialize expenseModel before the loop and use it inside the loop for all the rows:
ExpenseModel expenseModel=new ExpenseModel();
Move that line inside the loop:
do {
ExpenseModel expenseModel=new ExpenseModel();
expenseModel.setTitle(cursor.getString(cursor.getColumnIndex(COLUMN_EXPENSE_TITLE)));
expenseModel.setDescription(cursor.getString(cursor.getColumnIndex(COLUMN_EXPENSE_DESCRIPTION)));
expenseModel.setAmount(cursor.getInt(cursor.getColumnIndex(COLUMN_EXPENSE_AMOUNT)));
expenseModel.setDate(cursor.getString(cursor.getColumnIndex(COLUMN_EXPENSE_DATE)));
expenseModel.setCurrency(cursor.getString(cursor.getColumnIndex(COLUMN_EXPENSE_CURRENCY)));
Log.v("Info : ",""+cursor.getString(cursor.getColumnIndex(COLUMN_EXPENSE_TITLE)));
expenseModels.add(expenseModel)
}while (cursor.moveToNext());
Using Hibernate 3.6.0
I'm having a real hard time understanding hibernate. I keep running into this issue with lazy initialization exception.
I have an Event entity with a one-to-many relationship with RSVP. When a run a test get back a list of events it works. But when I'm making the call in my controller in order to return it as json, I run into this lazy init error.
This is my event class
#Entity
#Table(name = "EVENT")
public class Event implements Serializable {
#SequenceGenerator(name="event", sequenceName="EVENT_PK_SEQ")
#GeneratedValue(generator="event",strategy=GenerationType.SEQUENCE)
#Id
#Column(name = "EVENT_ID")
private int id;
#Column(name = "DATE_TIME")
private Date date;
#Column(name = "EVENT_NAME")
private String name;
#Column(name = "EVENT_PARTICIPANT_LIMIT")
private int limit;
#Column(name = "EVENT_VISIBILITY")
private boolean visibilty;
#Column(name = "EVENT_LOCATION")
private String location;
#Column(name = "EVENT_DESCRIPTION")
private String description;
#OneToOne(cascade=CascadeType.REMOVE, fetch= FetchType.EAGER)
private User author;
private Date create_date;
#OneToOne(cascade=CascadeType.REMOVE, fetch= FetchType.EAGER)
private EventType eventType;
#OneToOne(cascade=CascadeType.REMOVE, fetch= FetchType.EAGER)
private EventClass eventClass;
#OneToMany(cascade = CascadeType.ALL)
private Set<RSVP> rsvps = new HashSet<RSVP>();
#ManyToMany(mappedBy="event")
private Set<Group> groups = new HashSet<Group>();
public Event(int id, Date date, String name, int limit, boolean visibilty, String location, String description,
User author, Date create_date, EventType eventType, EventClass eventClass) {
super();
this.id = id;
this.date = date;
this.name = name;
this.limit = limit;
this.visibilty = visibilty;
this.location = location;
this.description = description;
this.author = author;
this.create_date = create_date;
this.eventType = eventType;
this.eventClass = eventClass;
}
public Event(){
super();
}
#Override
public String toString() {
return "Event [id=" + id + ", date=" + date + ", name=" + name + ", limit=" + limit + ", visibilty=" + visibilty
+ ", location=" + location + ", description=" + description + ", author=" + author + ", create_date="
+ create_date + ", eventType=" + eventType + ", eventClass=" + eventClass + ", rsvps=" + rsvps
+ ", groups=" + groups + "]";
}
public User getAuthor() {
return author;
}
public void setAuthor(User author) {
this.author = author;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getLimit() {
return limit;
}
public void setLimit(int limit) {
this.limit = limit;
}
public boolean isVisibilty() {
return visibilty;
}
public void setVisibilty(boolean visibilty) {
this.visibilty = visibilty;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Date getCreate_date() {
return create_date;
}
public void setCreate_date(Date create_date) {
this.create_date = create_date;
}
public EventType getEventType() {
return eventType;
}
public void setEventType(EventType eventType) {
this.eventType = eventType;
}
public EventClass getEventClass() {
return eventClass;
}
public void setEventClass(EventClass eventClass) {
this.eventClass = eventClass;
}
public Set<RSVP> getRsvps() {
return rsvps;
}
public void setRsvps(Set<RSVP> rsvps) {
this.rsvps = rsvps;
}
public Set<Group> getGroups() {
return groups;
}
public void setGroups(Set<Group> groups) {
this.groups = groups;
}
}
My RSVP
#Entity
#Table(name="RSVP")
public class RSVP {
#Id
#Column(name="RSVP_ID")
#SequenceGenerator(name="rsvp", sequenceName="RSVP_PK_SEQ")
#GeneratedValue(generator="rsvp",strategy=GenerationType.SEQUENCE)
private int rsvpId;
#OneToOne(cascade=CascadeType.REMOVE, fetch= FetchType.EAGER)
#JoinColumn(name="STATUS_ID")
private RSVPStatus status;
#ManyToOne(cascade=CascadeType.REMOVE)
#JoinColumn(name="USER_ID")
private User user;
#ManyToOne(fetch=FetchType.EAGER)
#JoinColumn(name="EVENT_ID")
private Event event;
public RSVP(int rsvpId, RSVPStatus status, User user, Event event) {
super();
this.rsvpId = rsvpId;
this.status = status;
this.user = user;
this.event = event;
}
public RSVP() {
}
#Override
public String toString() {
return "RSVP [rsvpId=" + rsvpId + ", status=" + status + ", user=" + user + ", event=" + event + "]";
}
public int getRsvpId() {
return rsvpId;
}
public void setRsvpId(int rsvpId) {
this.rsvpId = rsvpId;
}
public RSVPStatus getStatus() {
return status;
}
public void setStatus(RSVPStatus status) {
this.status = status;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public Event getEvent() {
return event;
}
public void setEvent(Event event) {
this.event = event;
}
}
MY controller
public class MyController {
private static SessionFactory sf = HibernateUtils.getSessionFactory();
private DataFacade df = new DataFacade(sf);
#RequestMapping(value="home", method=RequestMethod.GET,
consumes= MediaType.APPLICATION_JSON_VALUE)
#ResponseBody
public ResponseEntity<List<Event>> getUserCal(){
DataFacade df = new DataFacade(sf);
List<Event> events= df.getAllEventsByAuthor(1);
for(Event e:events){
System.out.println(e);
}
return new ResponseEntity<List<Event>>(events,HttpStatus.OK);
}
}
Your RSVP collection is fetched lazily. (If you don't specify a fetch type, the default is lazy). You need to change it to eager if you are planning to access it after the Hibernate session is closed:
#OneToMany(cascade = CascadeType.ALL, fetch= FetchType.EAGER)
private Set<RSVP> rsvps = new HashSet<RSVP>();
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 + "'" +
'}';
}
}
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.