I have created an entity of a table with name Category and I want to get the data as an entity and display the name of the category into a choicebox using StringConverter.
The problem is when I call addAll() method, it occurs a NullPointerException.
Here is my code:
private ChoiceBox<Category> chbDisplayCustomCategory;
#Override
public void initialize(URL location, ResourceBundle resources) {
emFactory = Persistence.createEntityManagerFactory("Glory_StorePU");
eManager = emFactory.createEntityManager();
Query query = eManager.createNamedQuery("Category.findAll", Category.class);
List<Category> list = query.getResultList();
ObservableList<Category> result=FXCollections.observableArrayList(list);
chbDisplayCustomCategory.getItems().addAll(result);
}
Here is the Entity class (Automatically generated):
package MainPack.Entities;
import java.io.Serializable;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.xml.bind.annotation.XmlRootElement;
#Entity
#Table(name = "CATEGORY")
#XmlRootElement
#NamedQueries({
#NamedQuery(name = "Category.findAll", query = "SELECT c FROM Category c"),
#NamedQuery(name = "Category.findById", query = "SELECT c FROM Category c WHERE c.id = :id"),
#NamedQuery(name = "Category.findByCatName", query = "SELECT c FROM Category c WHERE c.catName = :catName")})
public class Category implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Basic(optional = false)
#Column(name = "ID")
private Long id;
#Basic(optional = false)
#Column(name = "CAT_NAME")
private String catName;
public Category() {
}
public Category(Long id) {
this.id = id;
}
public Category(Long id, String catName) {
this.id = id;
this.catName = catName;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getCatName() {
return catName;
}
public void setCatName(String catName) {
this.catName = catName;
}
#Override
public int hashCode() {
int hash = 0;
hash += (id != null ? id.hashCode() : 0);
return hash;
}
#Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Category)) {
return false;
}
Category other = (Category) object;
if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
return false;
}
return true;
}
#Override
public String toString() {
return "MainPack.Entities.Category[ id=" + id + " ]";
}
}
so can you help me please ?
Related
I was trying to add data to my tableView in my JavaFX app. I am using hibernate to do operations on my Database. I used a query to get all the orders and store each order in an object and added the object to the observable list of the tableView. I created the orders class and mapped it to my database. This is the class of the orders:
#Entity
#Table(name = "orders")
public class orders implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "order_id")
private int order_id;
#JoinColumn(name = "item_id")
#ManyToOne
#NotNull
private items item_id;
#Column(name = "quantity")
#NotNull
private int quantity;
#Column(name = "price_per_unit")
#NotNull
private double price_per_unit;
#Column(name = "total_price")
#NotNull
private double total_price;
#Column(name = "order_date")
#NotNull
private Date order_date;
#JoinColumn(name = "user_id")
#ManyToOne
#NotNull
private users user_id;
public orders() {
}
public orders(int order_id, items item_id, int quantity, double price_per_unit, double total_price, Date order_date, users user_id) {
this.order_id = order_id;
this.item_id = item_id;
this.quantity = quantity;
this.price_per_unit = price_per_unit;
this.total_price = total_price;
this.order_date = order_date;
this.user_id = user_id;
}
public int getOrder_id() {
return order_id;
}
public void setOrder_id(int order_id) {
this.order_id = order_id;
}
public items getItem_id() {
return item_id;
}
public void setItem_id(items item_id) {
this.item_id = item_id;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
public double getPrice_per_unit() {
return price_per_unit;
}
public void setPrice_per_unit(double price_per_unit) {
this.price_per_unit = price_per_unit;
}
public double getTotal_price() {
return total_price;
}
public void setTotal_price(double total_price) {
this.total_price = total_price;
}
public Date getOrder_date() {
return order_date;
}
public void setOrder_date(Date order_date) {
this.order_date = order_date;
}
public users getUser_id() {
return user_id;
}
public void setUser_id(users user_id) {
this.user_id = user_id;
}
}
And the below code is the code of the view in which I have the tableView that loads the orders and displays the orders from the database:
public class OrdersPageController implements Initializable {
private Main app;
private Session session;
private Transaction transaction = null;
#FXML
private TableView<orders> table;
public void setApp(Main app) {
this.app = app;
}
/**
* Initializes the controller class.
*/
#Override
public void initialize(URL url, ResourceBundle rb) {
session = HibernateUtil.getSessionFactory().openSession();
transaction = session.beginTransaction();
//Fill the table view
getOrders();
}
public void goBack(ActionEvent event){
session.close();
transaction = null;
app.goToHomePage();
}
public void processLogout(ActionEvent event){
session.close();
transaction = null;
app.userLogout();
}
public void addOrder(ActionEvent event){
session.close();
transaction = null;
app.addOrdersPage();
}
public void deleteOrder(ActionEvent event){
session.close();
transaction = null;
app.closeOrdersPage();
}
public void getOrders(){
try{
String hql = "FROM orders";
Query query = session.createQuery(hql);
List<orders> list = query.getResultList();
for (orders o : list) {
//Create an order object
orders order = new orders();
order.setOrder_id(o.getOrder_id());
order.setItem_id(o.getItem_id());
order.setPrice_per_unit(o.getPrice_per_unit());
order.setQuantity(o.getQuantity());
order.setOrder_date(o.getOrder_date());
order.setTotal_price(o.getTotal_price());
order.setUser_id(o.getUser_id());
//Create an observable list for the table
ObservableList<orders> tableList = table.getItems();
//Add the order object to the list
tableList.add(order);
//Set the created list to the table to show data
table.setItems(tableList);
}
}catch(Exception e){
System.out.println(e.getMessage());
}
finally{
session.close();
}
}
}
Note that the getOrders method is the method that gets the orders from the database and sets the observable list of the tableView.
I am having problem displaying the item_id and the user_id of the order. I think the problem is that they both are objects of type items and users respectively and the table displays the address of the objects. Instead I want to display the numbers of the ids of the item ordered and the user that made the order. If you know what I can do to fix my problem please share it with me.
Add cellFactorys to the relevant columns. You haven't shown the FXML in the question, so I don't know the names you assigned to the appropriate TableColumn instances, but you can do something like this:
public class OrdersPageController implements Initializable {
// ...
#FXML
private TableView<orders> table;
#FXML
private TableColumn<orders, users> userColumn ;
#Override
public void initialize(URL url, ResourceBundle rb) {
userColumn.setCellFactory(tc -> new TableCell<>() {
#Override
protected void updateItem(users user, boolean empty) {
super.updateItem(user, empty);
if (empty || user == null) {
setText("");
} else {
String text = /* anything you need based on user */
setText(text);
}
}
});
session = HibernateUtil.getSessionFactory().openSession();
transaction = session.beginTransaction();
//Fill the table view
getOrders();
}
}
Just override toString method in users and items Classes:
Example: in your users Class ->
#Override
public String toString() {
return user_id.toString();
}
As James_D stated, have a look on java conventions. Java Classes should be always be with Capital Letter.
I am trying to achieve many-to-many relationship in Room Persistence Library. I am trying to create a Notes App with Tags.
The idea is:
A note will have multiple tags.
A tag will have multiple notes.
Show all notes in RecyclerView along with Tags.
To achieve this, I have created two models Note.java, Tag.java and TagJoin model to store the relationship b/w notes and tags. Achieving one-to-one is very easy using #Relation annotation.
Here are my models
#Entity(tableName = "notes")
public class Note {
#PrimaryKey
#NonNull
public final String id;
#ColumnInfo(name = "note")
public String note;
#Ignore
public List<Tag> tags;
#Ignore
public Note(String note) {
this(UUID.randomUUID().toString(), note);
}
public Note(String id, String note) {
this.id = id;
this.note = note;
}
public String getId() {
return id;
}
public String getNote() {
return note;
}
public void setNote(String note) {
this.note = note;
}
public List<Tag> getTags() {
return tags;
}
public void setTags(List<Tag> tags) {
this.tags = tags;
}
#Entity(tableName = "note_tag_join",
primaryKeys = {"noteId", "tagId"},
foreignKeys = {
#ForeignKey(
entity = Note.class,
parentColumns = "id",
childColumns = "noteId",
onDelete = CASCADE),
#ForeignKey(
entity = Tag.class,
parentColumns = "id",
childColumns = "tagId",
onDelete = CASCADE)},
indices = {
#Index(value = "noteId"),
#Index(value = "tagId")
}
)
public static class TagJoin {
#NonNull
public final String noteId;
#NonNull
public final String tagId;
public TagJoin(String noteId, String tagId) {
this.noteId = noteId;
this.tagId = tagId;
}
}
}
Tags Model:
#Entity(tableName = "tags", indices = {#Index(value = "name", unique = true)})
public class Tag {
#PrimaryKey
#NonNull
public String id;
#ColumnInfo(name = "name")
public String name;
#Ignore
public Tag(String name) {
this(UUID.randomUUID().toString(), name);
}
public Tag(String id, String name) {
this.id = id;
this.name = name;
}
public String getId() {
return id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Notes Dao:
#Dao
public interface NoteDao {
#Query("SELECT * FROM notes ORDER BY id DESC")
LiveData<List<Note>> getAllNotes();
#Insert
long insert(Note note);
#Update
void update(Note note);
#Delete
void delete(Note note);
#Query("DELETE FROM notes")
void deleteAll();
#Query("SELECT COUNT(*) FROM notes")
int getNotesCount();
#Query("SELECT notes.* FROM notes\n" +
"INNER JOIN note_tag_join ON notes.id=note_tag_join.noteId\n" +
"WHERE note_tag_join.tagId=:tagId")
List<Note> getAllNotesOfTag(String tagId);
#Insert
void insert(Note.TagJoin... joins);
#Delete
void delete(Note.TagJoin... joins);
}
So far everything is good. Now I want to show the Notes in RecyclerView but I can't find a way to fetch all Notes along with Tags at once. One way is, getting the tags of each note in onBindViewHolder method which I think is wrong as we have to query the db each time row is displayed.
Please provide me suggestions.
PS: I have followed the code provided in this article
https://commonsware.com/AndroidArch/previews/mn-relations-in-room
In objectify, when I define a collection property with String datatype,
#IgnoreSave(IfEmpty.class)
private Set<String> collectionProperty = new HashSet<>();
and then look at a record in datastore, it appears indexed even though I have not annotated it with #Index.
Contrary, when I use a complex Object instead String, it does not appear as indexed.
Why are Collection properties indexed sometimes and sometimes not? And is there a way to determine this?
--
Unmodified code and screenshot from admin console/datastore:
#Entity
#Cache(expirationSeconds = 900)
public class Item extends StringId implements Serializable {
private static final Logger log = Logger.getLogger(Item.class.getSimpleName());
private static final long serialVersionUID = 1;
// Constructors
private Item() {}
#Nonnull
private static Item create(#Nonnull String itemId) {
Item item = (Item) new Item().setId(itemId);
item.piecesFromId();
log.info("item = " + JsonHelper.logToJson(item));
return item;
}
#Nonnull
public static Item create(#Nonnull String provider, #Nonnull String type, #Nonnull String identifier) {
String itemId = IdHelper.createItemId(provider, type, identifier);
Item item = ((Item) new Item().setId(itemId))
.setProvider(provider)
.setType(type)
.setIdentifier(identifier);
log.info("item = " + JsonHelper.logToJson(item));
return item;
}
#Nonnull
public static Item loadOrCreate(#Nonnull String itemId) {
Item item = ofy().load().type(Item.class).id(itemId).now();
if (item == null) {
item = Item.create(itemId);
}
return item;
}
#Nullable
public static Item load(#Nonnull String itemId) {
return ofy().load().type(Item.class).id(itemId).now();
}
#OnLoad
private void piecesFromId() {
provider = IdHelper.getProvider(id);
type = IdHelper.getType(id);
identifier = IdHelper.getIdentifier(id);
}
public Item save() {
ofy().defer().save().entity(this);
return this;
}
#OnSave
private void integrity() {
if (id == null) { throw new RuntimeException("Id must not be null."); }
if (itemPreview == null) { throw new RuntimeException("itemPreview must not be null."); }
if (provider == null || type == null || identifier == null) { throw new RuntimeException("provider, type and identifier must not be null."); }
if (!id.equals(IdHelper.createItemId(provider, type, identifier))) { throw new RuntimeException("id does not coincide with provider, type and identifier."); }
if (!id.equals(itemPreview.getItemId())) { throw new RuntimeException("id does not coincide with id in itemPreview."); }
}
#OnSave
private void timestamp() {
if (created == null) {
created = System.currentTimeMillis();
}
}
// Properties
#Ignore
private String provider;
#Ignore
private String type;
#Ignore
private String identifier;
#Ignore // json
private ItemPreview itemPreview;
#ApiResourceProperty(ignored = AnnotationBoolean.TRUE)
#IgnoreSave(IfEmpty.class)
private Set<String> subscribedUserIds = new HashSet<>();
#ApiResourceProperty(ignored = AnnotationBoolean.TRUE)
#IgnoreSave(IfEmpty.class)
private Set<String> notifyUserIds = new HashSet<>();
#ApiResourceProperty(ignored = AnnotationBoolean.TRUE)
#IgnoreSave(IfEmpty.class)
private Set<String> blacklistingUserIds = new HashSet<>();
#ApiResourceProperty(ignored = AnnotationBoolean.TRUE)
private Long created;
#ApiResourceProperty(ignored = AnnotationBoolean.TRUE)
#IgnoreSave(IfDefault.class)
#Index
private Status status = Status.ACTIVE;
#ApiResourceProperty(ignored = AnnotationBoolean.TRUE)
#IgnoreSave(IfNull.class)
private String suspensionNotice;
// Json
#ApiResourceProperty(ignored = AnnotationBoolean.TRUE)
#IgnoreSave(IfNull.class)
private String itemPreviewJson;
private static Type itemPreviewType = new TypeToken<ItemPreview>(){}.getType();
#OnLoad
private void itemPreviewFromJson() {
if (itemPreviewJson != null) {
itemPreview = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create()
.fromJson(itemPreviewJson, itemPreviewType);
}
}
#OnSave
private void itemPreviewToJson() {
itemPreviewJson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create()
.toJson(itemPreview, itemPreviewType);
}
// Accessors
public String getProvider() {
return provider;
}
public Item setProvider(String provider) {
this.provider = provider;
return this;
}
public String getType() {
return type;
}
public Item setType(String type) {
this.type = type;
return this;
}
public String getIdentifier() {
return identifier;
}
public Item setIdentifier(String identifier) {
this.identifier = identifier;
return this;
}
public ItemPreview getItemPreview() {
return itemPreview;
}
public Item setItemPreview(ItemPreview itemPreview) {
this.itemPreview = itemPreview;
return this;
}
public Set<String> getSubscribedUserIds() {
return subscribedUserIds;
}
public Item setSubscribedUserIds(Set<String> subscribedUserIds) {
this.subscribedUserIds = subscribedUserIds;
return this;
}
public Set<String> getNotifyUserIds() {
return notifyUserIds;
}
public Item setNotifyUserIds(Set<String> notifyUserIds) {
this.notifyUserIds = notifyUserIds;
return this;
}
public Set<String> getBlacklistingUserIds() {
return blacklistingUserIds;
}
public Item setBlacklistingUserIds(Set<String> blacklistingUserIds) {
this.blacklistingUserIds = blacklistingUserIds;
return this;
}
public Long getCreated() {
return created;
}
public Item setCreated(Long created) {
this.created = created;
return this;
}
public Status getStatus() {
return status;
}
public Item setStatus(Status status) {
this.status = status;
return this;
}
public String getSuspensionNotice() {
return suspensionNotice;
}
public Item setSuspensionNotice(String suspensionNotice) {
this.suspensionNotice = suspensionNotice;
return this;
}
// Collections
public static Map<String, Item> loadAll(Set<String> itemIds) {
return ofy().load().type(Item.class).ids(itemIds);
}
}
I made an application with an SQLite database. I want to show the data in a listview, but I don't want to show all the data from the database, but just some data. So, I want to add a condition. I only want to show the data where string 'dag' is 'maandag'.
Can anyone help me?
This is the code from my DatabaseHelper, where the database is created:
package com.persoonlijk.rooster.test2;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteStatement;
import java.util.ArrayList;
import java.util.List;
//A helper class to manage database creation and version management.
public class DataManipulator
{
//Database attributes
private static final String DATABASE_NAME = "mydatabase.db";
static final String TABLE_NAME = null;
private static final int DATABASE_VERSION = 12;
//Table attributes
public static final String KEY_ROWID = "id";
public static final String KEY_DAG = "dag";
public static final String KEY_UUR = "uur";
public static final String KEY_VAK = "vak";
public static final String KEY_LOKAAL = "lokaal";
private static Context context;
static SQLiteDatabase db;
private SQLiteStatement insertStmt;
private static final String INSERT = "insert into " + TABLE_NAME + " (dag,uur,vak,lokaal) values (?,?,?,?)";
public DataManipulator(Context context) {
DataManipulator.context = context;
OpenHelper openHelper = new OpenHelper(DataManipulator.context);
DataManipulator.db = openHelper.getWritableDatabase();
this.insertStmt = DataManipulator.db.compileStatement(INSERT);
}
public long insert(String dag,String uur,String vak,String lokaal) {
this.insertStmt.bindString(1, dag);
this.insertStmt.bindString(2, uur);
this.insertStmt.bindString(3, vak);
this.insertStmt.bindString(4, lokaal);
return this.insertStmt.executeInsert();
}
public void deleteAll() {
db.delete(TABLE_NAME, null, null);
}
public List<String[]> selectAll()
{
List<String[]> list = new ArrayList<String[]>();
Cursor cursor = db.query(TABLE_NAME, new String[] { "id","dag","uur","vak","lokaal" }, null, null, null, null, "dag asc");
int x=0;
if (cursor.moveToFirst()) {
do {
String[] b1=new String[]{cursor.getString(0),cursor.getString(1),cursor.getString(2),
cursor.getString(3),cursor.getString(4)};
list.add(b1);
x=x+1;
} while (cursor.moveToNext());
}
if (cursor != null && !cursor.isClosed()) {
cursor.close();
}
cursor.close();
return list;
}
public boolean delete(long id) {
return db.delete(TABLE_NAME, KEY_ROWID + "=" + id, null) > 0;
}
private static class OpenHelper extends SQLiteOpenHelper {
OpenHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + TABLE_NAME + " (id INTEGER PRIMARY KEY, dag TEXT, uur TEXT, vak TEXT, lokaal TEXT)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
}
}
This is the code from the Activity where I want to display the specific data. Right now, all the data from the database is displayed.
package com.persoonlijk.rooster.test2;
import java.util.ArrayList;
import java.util.List;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
public class RoosterMaandag extends ListActivity{
TextView selection;
public int idToModify;
DataManipulator dm;
List<String[]> list = new ArrayList<String[]>();
List<String[]> names2 =null ;
String[] stg1;
/** Called when the activity is first created. */
//zorgt voor het overzicht van de gegevens uit de database
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.rooster);
dm = new DataManipulator(this);
names2 = dm.selectAll();
stg1=new String[names2.size()];
int x=0;
String stg;
for (String[] dag : names2) {
stg = dag[1]+" - "+dag[2]+ " - "+dag[3]+" - "+dag[4];
stg1[x]=stg;
x++;
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,stg1);
this.setListAdapter(adapter);
selection=(TextView)findViewById(R.id.selection);
}
//menuknoppen
#Override
public boolean onCreateOptionsMenu(Menu menu) {
menu.add(Menu.NONE, 0, 0, "Voeg gegevens toe");
menu.add(Menu.NONE, 1, 1, "Verwijder gegevens");
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case 0:
startActivity(new Intent(this, SaveData.class));
return true;
case 1:
startActivity(new Intent(this, VerwijderData.class));
return true;
}
return false;
}
}
Please let me know when my question isn't clear enough. I really hope someone can help me!
I added this code in my DataManipulator.java:
public List<String[]> selectSome(String arg) {
String[] columns = new String[] { "id", "dag", "uur", "vak", "lokaal" };
String[] selectionArgs = {arg};
Cursor cursor = db.query(TABLE_NAME, columns, "dag = ?", selectionArgs, null, null, "dag asc");
List<String[]> list = new ArrayList<String[]>(cursor.getCount());
while (cursor.moveToNext()) {
String[] b1 = new String[] { cursor.getString(0),
cursor.getString(1), cursor.getString(2),
cursor.getString(3), cursor.getString(4) };
list.add(b1);
}
cursor.close();
return list;
}
and this code in my RoosterMaandag.java:
public void onCreate(Bundle savedInstanceState){
....
dm.selectSome("maandag");
....
}
I don't know about android but for sql
try this
select data_to_print from table_name where REGEXP_LIKE(column_name_where_to_match,'dag$');
more info here http://docs.oracle.com/cd/B12037_01/server.101/b10759/ap_posix001.htm#i690819
Example:
SQL> select job_id from jobs where regexp_like(job_id,'N$');
JOB_ID
----------
MK_MAN
PU_MAN
SA_MAN
ST_MAN
you need a new method in your DataManipulator class:
public List<String[]> selectSome(String arg) {
String[] columns = new String[] { "id", "dag", "uur", "vak", "lokaal" };
String[] selectionArgs = {arg};
Cursor cursor = db.query(TABLE_NAME, columns, "dag = ?", selectionArgs, null, null, "dag asc");
List<String[]> list = new ArrayList<String[]>(cursor.getCount());
while (cursor.moveToNext()) {
String[] b1 = new String[] { cursor.getString(0),
cursor.getString(1), cursor.getString(2),
cursor.getString(3), cursor.getString(4) };
list.add(b1);
}
cursor.close();
return list;
}
I'll say it again. consider using a CursorAdapter for these tasks.
I use spring-data-solr to integrate spring-data-jpa with solr, but when i use SolrOperations to saveBean(org.domain.Article), an exception throws:
org.springframework.data.solr.UncategorizedSolrException: Failed to convert from type org.kb.domain.Article to type org.apache.solr.common.SolrInputDocument for value 'Article [id=1,title=test-1, description=test-1, content=test-1, author=test-1, link=test-1, attachment=test-1, date=Sat Jan 05 20:06:12 CST 2013, category=org.kb.domain.Category#67e6cf07]'; nested exception is org.apache.solr.client.solrj.beans.BindingException: Invalid setter method. Must have one and only one parameter; nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type org.kb.domain.Article to type org.apache.solr.common.SolrInputDocument for value 'Article [id=1,title=test-1, description=test-1, content=test-1, author=test-1, link=test-1, attachment=test-1, date=Sat Jan 05 20:06:12 CST 2013, category=org.kb.domain.Category#67e6cf07]'; nested exception is org.apache.solr.client.solrj.beans.BindingException: Invalid setter method. Must have one and only one parameter
here is my bean:
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import org.apache.solr.client.solrj.beans.Field;
import com.fasterxml.jackson.annotation.JsonFormat;
#Entity
#Table(name="article")
public class Article extends IdEntity{
private static final long serialVersionUID = -5170398606065544445L;
private String title;
private String description;
private String content;
private String author;
private String link;
private String attachment;
private Date date;
private Category category;
public Article() {
super();
}
#ManyToOne
#JoinColumn(name="category_id")
public Category getCategory() {
return category;
}
public void setCategory(Category category) {
this.category = category;
}
#Column(name="title")
#Field("title")
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
#Column(name="description")
#Field("description")
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
#Column(name="content")
#Field("content")
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
#Column(name="author")
#Field("author")
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
#Column(name="link")
#Field("link")
public String getLink() {
return link;
}
public void setLink(String link) {
this.link = link;
}
#Column(name="attachment")
#Field("attachment")
public String getAttachment() {
return attachment;
}
public void setAttachment(String attachment) {
this.attachment = attachment;
}
#Column(name="date")
#JsonFormat(pattern="yyyy-MM-dd", timezone="GMT+08:00")
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
#Override
public String toString() {
return "Article [id=" + id + ",title=" + title + ", description=" + description
+ ", content=" + content + ", author=" + author + ", link="
+ link + ", attachment=" + attachment + ", date=" + date
+ ", category=" + category + "]";
}
}
import java.io.Serializable;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.MappedSuperclass;
import org.apache.solr.client.solrj.beans.Field;
#MappedSuperclass
public abstract class IdEntity implements Serializable{
/**
*
*/
private static final long serialVersionUID = -5676694680777491651L;
protected Long id;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Field("id")
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
}
The problem is in your solrj Field annotation. Have a look at the documentation:
The #Field annotation can be applied to a field or a setter method.
You should move the Field annotation to the either the setId setter method or the id field itself. You can even remove the id qualifier since the field name is already id, that's enough:
#Field
protected Long id;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}