Hi guys i'me having troubles using morphia for mongodb this is what im creating.
Im creating a spigot plugin for my hub server and im using mongodb with morphia for store my user object to my collection and this object only store 1 user instead of saving all users into the collection.
My user object
#Entity(value = "clientdata", noClassnameStored = true)
public class ClientData {
#Id
public int id;
#Indexed(options = #IndexOptions(unique = true))
private String uuid;
#Indexed
private String lastName, username, lastLoginDate, ip;
#Indexed
private int level, exp, joins, coins, pearls;
#Property("hats")
private List<Integer> hatsOwned;
public ClientData(){
this.hatsOwned = new ArrayList<>();
if(this.hatsOwned.isEmpty()){
this.hatsOwned.add(0);
}
}
public int getId() {
return id;
}
public String getIp() {
return ip;
}
public void setIp(String ip) {
this.ip = ip;
}
public void setId(int id) {
this.id = id;
}
public String getUuid() {
return uuid;
}
public void setUuid(String uuid) {
this.uuid = uuid;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public int getLevel() {
return level;
}
public void setLevel(int level) {
this.level = level;
}
public int getExp() {
return exp;
}
public void setExp(int exp) {
this.exp = exp;
}
public int getJoins() {
return joins;
}
public void setJoins(int joins) {
this.joins = joins;
}
public void addJoins(int joins) {
this.joins += joins;
}
public int getCoins() {
return coins;
}
public void setCoins(int coins) {
this.coins = coins;
}
public int getPearls() {
return pearls;
}
public void setPearls(int pearls) {
this.pearls = pearls;
}
public List<Integer> getHatsOwned() {
return hatsOwned;
}
public void setHatsOwned(List<Integer> hatsOwned) {
this.hatsOwned = hatsOwned;
}
public void addNewHatOwned(int hatID){
this.hatsOwned.add(hatID);
}
public String getLastLoginDate() {
return lastLoginDate;
}
public void setLastLoginDate(String lastLoginDate) {
this.lastLoginDate = lastLoginDate;
}
}
My mongo manager class
public class MongoManager {
private static MongoManager ins = new MongoManager();
private MongoClient mc;
private Morphia morphia;
private Datastore datastore;
private ClientDAO userDAO;
public static MongoManager get() {
return ins;
}
public void init() {
ServerAddress addr = new ServerAddress("127.0.0.1", 27017);
List<MongoCredential> credentials = new ArrayList<>();
credentials.add(MongoCredential.createCredential("union", "admin", "union16".toCharArray()));
mc = new MongoClient(addr, credentials);
morphia = new Morphia();
morphia.map(ClientData.class);
datastore = morphia.createDatastore(mc, "admin");
datastore.ensureIndexes();
userDAO = new ClientDAO(ClientData.class, datastore);
}
public void disconnect(){
this.mc.close();
}
public ClientData getUserByPlayer(Player player) {
ClientData du = userDAO.findOne("uuid", player.getUniqueId().toString());
long time = System.currentTimeMillis();
if (du == null) {
du = new ClientData();
du.setUuid(player.getUniqueId().toString());
du.setCoins(0);
du.setExp(0);
du.setJoins(0);
du.setLastLoginDate(DateFormat.getTimeInstance().format(time));
du.setLevel(0);
du.setPearls(0);
du.setIp(player.getAddress().getAddress().toString());
du.setUsername(player.getDisplayName());
du.setLastName(player.getName());
du.setHatsOwned(null);
userDAO.save(du);
}
return du;
}
public void saveUser(ClientData user) {
userDAO.save(user);
}
public List<ClientData> getAllUsers() {
return userDAO.find().asList();
}
}
You can't insert more than one because you have duplicateKey: you can't use an #id with primitive type without setting a unique value yourself.
You defined your id like this:
#Id
public int id;
Even though you never set any value for id, primitive types are initialized to 0, so you end up trying to insert multiple documents with the same key.
Solution:
You can either :
change your id to String: #Id String id;
change your id to ObjectId: #Id ObjectId id;
keep #Id int id and manually set a unique value to it (player.getUniqueId() for instance).
The first 2 options will work because they won't be initialized and will be null. Mongo will then generate a unique id for you.
Related
I have query:
public List<InvoiceItems> findAllBalance(String external_key) throws HibernateException {
return (List<InvoiceItems>) session.createQuery("select SUM(i.amount) as amount, t.record_id from Accounts a, InvoiceItems i, Tenant t WHERE a.record_id = i.account_record_id AND t.record_id=a.tenant_record_id AND a.external_key='"+external_key+"' group by i.tenant_record_id, t.record_id").list();
}
InvoiceItems.java:
package id.co.keriss.consolidate.ee;
import java.util.Date;
import org.jpos.ee.Accounts;
public class InvoiceItems {
private long record_id;
private String id;
private String type;
private String invoice_id;
private Accounts account_record_id;
private Tenant tenant_record_id;
private String description;
private long amount;
private Date created_date;
private String usage_name;
private String plan_name;
private String account_id;
public String getAccount_id() {
return account_id;
}
public void setAccount_id(String account_id) {
this.account_id = account_id;
}
public long getRecord_id() {
return record_id;
}
public void setRecord_id(long record_id) {
this.record_id = record_id;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getInvoice_id() {
return invoice_id;
}
public void setInvoice_id(String invoice_id) {
this.invoice_id = invoice_id;
}
public Accounts getAccount_record_id() {
return account_record_id;
}
public void setAccount_record_id(Accounts account_record_id) {
this.account_record_id = account_record_id;
}
public Tenant getTenant_record_id() {
return tenant_record_id;
}
public void setTenant_record_id(Tenant tenant_record_id) {
this.tenant_record_id = tenant_record_id;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public long getAmount() {
return amount;
}
public void setAmount(long amount) {
this.amount = amount;
}
public Date getCreated_date() {
return created_date;
}
public void setCreated_date(Date created_date) {
this.created_date = created_date;
}
public String getUsage_name() {
return usage_name;
}
public void setUsage_name(String usage_name) {
this.usage_name = usage_name;
}
public String getPlan_name() {
return plan_name;
}
public void setPlan_name(String plan_name) {
this.plan_name = plan_name;
}
}
then set to an variable:
List<InvoiceItems> invoiceItems = invoiceItemsDao.findAllBalance(jsonRecv.getString("externalkey"));
I want to get the value from that query, what I try:
LogSystem.info(request, "List : " + invoiceItems.get(0).getId();
I got an error "can't cast to InvoiceItems"
then I try changing from List<InvoiceItems> to just List
get with this :
LogSystem.info(request, "List : " + invoiceItems.get(0);
but the output like this not the value:
[Ljava.lang.Object;#41ea9df8
any advice? final result what i want is calculate amount of tenant
session.createQuery take HQL (Hibernate query language) however I see you use native SQL. Try using createSQLQuery method.
public List<InvoiceItems> findAllBalance(String external_key) throws HibernateException {
Query query = session.createSQLQuery("select SUM(i.amount) as amount, t.record_id from Accounts a, InvoiceItems i, Tenant t WHERE a.record_id = i.account_record_id AND t.record_id=a.tenant_record_id AND a.external_key='"+external_key+"' group by i.tenant_record_id, t.record_id");
query.setResultTransformer(Transformers.aliasToBean(InvoiceItems.class));
List<InvoiceItems> list = query.list();
return list;
}
i have this function to query in hibernate:
public List<TransactionQR> getAllTransaction() throws HibernateException {
return this.session.createQuery("SELECT id FROM TransactionQR").list();
}
then is success to show the data like this in html:
[2, 3]
but when i add more column in SELECT like this:
public List<TransactionQR> getAllTransaction() throws HibernateException {
return this.session.createQuery("SELECT id, codeqr FROM TransactionQR").list();
}
the result show like this:
[Ljava.lang.Object;#25026824, [Ljava.lang.Object;#170b75f9]
what is Ljava.lang.Object;#25026824 ? is return object, can i handle it to convert from list to json ?
i have model TransactionQR.java :
public class TransactionQR implements Serializable {
private Long id;
private String codeqr;
private Date approvaltime;
private String merchant;
private String code_merchant;
private Long amount;
private Long saldoawal;
private Integer tracenumber;
private String state;
private Date createdate;
private Batch batch;
public TransactionQR() {
}
public TransactionQR(Long id, String codeqr, Date approvaltime, String merchant, String code_merchant, Long amount,
Long saldoawal, Integer tracenumber, String state, Date createdate, Batch batch) {
super();
this.id = id;
this.codeqr = codeqr;
this.approvaltime = approvaltime;
this.merchant = merchant;
this.code_merchant = code_merchant;
this.amount = amount;
this.saldoawal = saldoawal;
this.tracenumber = tracenumber;
this.state = state;
this.createdate = createdate;
this.batch = batch;
}
public Long getId() {
return id;
}
public Date getApprovalTime() {
return approvaltime;
}
public Batch getBatch() {
return batch;
}
public void setBatch(Batch batch) {
this.batch = batch;
}
public void setApprovalTime(Date approvalTime) {
this.approvaltime = approvalTime;
}
public void setId(Long id) {
this.id = id;
}
public Date getApprovaltime() {
return approvaltime;
}
public void setApprovaltime(Date approvaltime) {
this.approvaltime = approvaltime;
}
public String getCodeqr() {
return codeqr;
}
public void setCodeqr(String codeqr) {
this.codeqr = codeqr;
}
public String getMerchant() {
return merchant;
}
public void setMerchant(String merchant) {
this.merchant = merchant;
}
public String getCode_merchant() {
return code_merchant;
}
public void setCode_merchant(String code_merchant) {
this.code_merchant = code_merchant;
}
public Long getAmount() {
return amount;
}
public void setAmount(Long amount) {
this.amount = amount;
}
public Long getSaldoawal() {
return saldoawal;
}
public void setSaldoawal(Long saldoawal) {
this.saldoawal = saldoawal;
}
public Integer getTracenumber() {
return tracenumber;
}
public void setTracenumber(Integer tracenumber) {
this.tracenumber = tracenumber;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public Date getCreatedate() {
return createdate;
}
public void setCreatedate(Date createdate) {
this.createdate = createdate;
}
}
the result is i want to show all data from database in list
In second case, since you are selecting two attributes, that is why session.createQuery("").list returns a list of object array(List<Object[]>) . At each index of list you will find an object array. Each array will have two indexes. First index will provide id while the second one would provide codeqr. So, basically you need to iterate over the list. Then fetch each value individually like arr[0], arr[1]..
I have created a spring boot project with mongodb , when i insert data into collection it get inserted but when i try to fetch from findOne by id the inserted value based on id it always returns null, I have given my model class and inserting method below,please tell me whats wrong
Account.java
#Document(collection = "account")
public class Account {
#Id
private long _id;
#Field("account_name")
private String accountName;
#Field("connector_type")
private String connectorType;
#Field("xsiURI1")
private String xsiURI1;
#Field("xsiURI2")
private String xsiURI2;
#Field("oci1")
private String OCI1;
#Field("oci2")
private String OCI2;
#Field("telcomadmin_username")
private String telcomadminUsername;
#Field("telcomadmin_password")
private String telcomadminPassword;
#Field("password_expdays")
private String passwordExpdays;
#Field("account_email_address")
private String accountEmailAddress;
#DateTimeFormat(iso = ISO.DATE_TIME)
#Field("inserted_date")
private Date insertedDate;
#DateTimeFormat(iso = ISO.DATE_TIME)
#Field("updated_date")
private Date updatedDate;
#Field("isActive")
private Boolean isActive;
public long get_id() {
return _id;
}
public void set_id(long _id) {
this._id = _id;
}
public String getXsiURI1() {
return xsiURI1;
}
public void setXsiURI1(String xsiURI1) {
this.xsiURI1 = xsiURI1;
}
public String getXsiURI2() {
return xsiURI2;
}
public void setXsiURI2(String xsiURI2) {
this.xsiURI2 = xsiURI2;
}
public String getOCI1() {
return OCI1;
}
public void setOCI1(String oCI1) {
OCI1 = oCI1;
}
public String getOCI2() {
return OCI2;
}
public void setOCI2(String oCI2) {
OCI2 = oCI2;
}
public String getAccountName() {
return accountName;
}
public void setAccountName(String accountName) {
this.accountName = accountName;
}
public String getConnectorType() {
return connectorType;
}
public void setConnectorType(String connectorType) {
this.connectorType = connectorType;
}
public String getTelcomadminUsername() {
return telcomadminUsername;
}
public void setTelcomadminUsername(String telcomadminUsername) {
this.telcomadminUsername = telcomadminUsername;
}
public String getTelcomadminPassword() {
return telcomadminPassword;
}
public void setTelcomadminPassword(String telcomadminPassword) {
this.telcomadminPassword = telcomadminPassword;
}
public String getPasswordExpdays() {
return passwordExpdays;
}
public void setPasswordExpdays(String passwordExpdays) {
this.passwordExpdays = passwordExpdays;
}
public String getAccountEmailAddress() {
return accountEmailAddress;
}
public void setAccountEmailAddress(String accountEmailAddress) {
this.accountEmailAddress = accountEmailAddress;
}
public Date getInsertedDate() {
return insertedDate;
}
public void setInsertedDate(Date insertedDate) {
this.insertedDate = insertedDate;
}
public Date getUpdatedDate() {
return updatedDate;
}
public void setUpdatedDate(Date updatedDate) {
this.updatedDate = updatedDate;
}
public Boolean getIsActive() {
return isActive;
}
public void setIsActive(Boolean isActive) {
this.isActive = isActive;
}
}
AccountsController.java
#RestController
#RequestMapping("/accounts")
#CrossOrigin("*")
public class AccountsController {
#Autowired
AccountsRepository accountsRepository;
#Autowired
SequenceRepository sequenceRepository;
private static final String ACCOUNT_SEQ_KEY = "accountsequence";
#PostMapping("/create")
public Account createAccount(#Valid #RequestBody Account account) {
account.set_id(sequenceRepository.getNextSequenceId(ACCOUNT_SEQ_KEY));
account.setIsActive(true);
return accountsRepository.save(account);
}
#GetMapping(value = "/findByID/{id}")
public ResponseEntity<Account> getAccountById(#PathVariable("id") String id) {
Account account = accountsRepository.findOne(id);
if (account == null) {
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
} else {
return new ResponseEntity<>(account, HttpStatus.OK);
}
}
}
AccountsRepository
public interface AccountsRepository {
List<Account> findAll(Sort sortByCreatedAtDesc);
Account save(Account account);
Account findOne(String id);
void delete(String id);
}
AccountsRepositoryIMPL
#Repository
public class AccountsRepositoryImpl implements AccountsRepository {
DBOperations dbOperations = new DBOperations();
#Override
public List<Account> findAll(Sort sortByCreatedAtDesc) {
Query q = new Query().with(new Sort(Sort.Direction.ASC, "inserted_date"));
List<Account> accountList = dbOperations.getMongoOpertion().findAllAndRemove(q, Account.class);
return accountList;
}
#Override
public Account save(Account account) {
try {
dbOperations.getMongoOpertion().save(account);
} catch (Exception e) {
e.printStackTrace();
}
return account;
}
#Override
public Account fin**strong text**dOne(String id) {
Account account = dbOperations.getMongoOpertion().findOne(Query.query(Criteria.where("_id").is(id)),
Account.class, "account");
return account;
}
#Override
public void delete(String id) {
Query query = new Query();
query.addCriteria(Criteria.where("id").is(id));
Account account = dbOperations.getMongoOpertion().findOne(query, Account.class);
dbOperations.getMongoOpertion().remove(account);
}
}
DBOperations.java
public class DBOperations {
ApplicationContext ctx = new GenericXmlApplicationContext("SpringConfig.xml");
public MongoOperations getMongoOpertion() {
MongoOperations mongoOperation = (MongoOperations) ctx.getBean("mongoTemplate");
return mongoOperation;
}
}
Look at your code.
You have declared _id as Long type.
#Id
private long _id;
But in your below methods you are passing String id to match the criteria.
So it is not working.
#Override
public Account findOne(String id) {
Account account = dbOperations.getMongoOpertion().findOne(Query.query(Criteria.where("_id").is(id)),
Account.class, "account");
return account;
}
#Override
public void delete(String id) {
Query query = new Query();
query.addCriteria(Criteria.where("id").is(id));
Account account = dbOperations.getMongoOpertion().findOne(query, Account.class);
dbOperations.getMongoOpertion().remove(account);
}
I'm having trouble trying to understand how realm.io persist/save objects.
I have 3 Objects (Inventory, InventoryItem and Product);
When I create a Inventory containing InventoryItems it works fine until i close the app. When i re-open the app all InventoryItems loses the reference to Product and start to show "null" instead.
Strange thing is all other attributes like Inventory reference to InventoryItem is persisted fine. Just problem with Products.
this is how i'm trying to do:
Model
Product
public class Product extends RealmObject {
#PrimaryKey
private String id;
#Required
private String description;
private int qtdUnityType1;
private int qtdUnityType2;
private int qtdUnityType3;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public int getQtdUnityType1() {
return qtdUnityType1;
}
public void setQtdUnityType1(int qtdUnityType1) {
this.qtdUnityType1 = qtdUnityType1;
}
public int getQtdUnityType2() {
return qtdUnityType2;
}
public void setQtdUnityType2(int qtdUnityType2) {
this.qtdUnityType2 = qtdUnityType2;
}
public int getQtdUnityType3() {
return qtdUnityType3;
}
public void setQtdUnityType3(int qtdUnityType3) {
this.qtdUnityType3 = qtdUnityType3;
}
}
Inventory
public class Inventory extends RealmObject {
#PrimaryKey
private String id;
#Required
private String type;
#Required
private Date createdAt;
#Required
private String status;
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
private RealmList<InventoryItem> listItems;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public Date getCreatedAt() {
return createdAt;
}
public void setCreatedAt(Date createdAt) {
this.createdAt = createdAt;
}
public RealmList<InventoryItem> getListItems() {
return listItems;
}
public void setListItems(RealmList<InventoryItem> listItems) {
this.listItems = listItems;
}
}
InventoryItem
public class InventoryItem extends RealmObject {
#PrimaryKey
private String idItem;
private Inventory inventory;
private Product product;
public Product getProduct() {
return product;
}
public void setProduct(Product product) {
this.product = product;
}
private Date expirationDate;
private int qtdUnityType1;
private int qtdUnityType2;
private int qtdUnityType3;
private int qtdDiscard;
public String getIdItem() {
return idItem;
}
public void setIdItem(String idItem) {
this.idItem = idItem;
}
public Inventory getInventory() {
return inventory;
}
public void setInventory(Inventory inventory) {
this.inventory = inventory;
}
public Date getExpirationDate() {
return expirationDate;
}
public void setExpirationDate(Date expirationDate) {
this.expirationDate = expirationDate;
}
public int getQtdUnityType1() {
return qtdUnityType1;
}
public void setQtdUnityType1(int qtdUnityType1) {
this.qtdUnityType1 = qtdUnityType1;
}
public int getQtdUnityType2() {
return qtdUnityType2;
}
public void setQtdUnityType2(int qtdUnityType2) {
this.qtdUnityType2 = qtdUnityType2;
}
public int getQtdUnityType3() {
return qtdUnityType3;
}
public void setQtdUnityType3(int qtdUnityType3) {
this.qtdUnityType3 = qtdUnityType3;
}
public int getQtdDiscard() {
return qtdDiscard;
}
public void setQtdDiscard(int qtdDiscard) {
this.qtdDiscard = qtdDiscard;
}
}
and finally one of the millions ways i tried to persist
realm.beginTransaction();
Inventory inventory = realm.createObject(Inventory.class);
inventory.setId(id);
inventory.setCreatedAt(new DateTime().toDate());
if (radioGroup.getCheckedRadioButtonId() == R.id.rbInventario) {
inventory.setType("Inventário");
} else {
inventory.setType("Validade");
}
inventory.setStatus("Aberto");
RealmList<InventoryItem> inventoryItems = new RealmList<>();
RealmResults<Product> productsRealmResults = realm.allObjects(Product.class);
for (int i = 1; i <= productsRealmResults.size(); i++) {
InventoryItem item = realm.createObject(InventoryItem.class);
item.setIdProduct(productsRealmResults.get(i - 1).getId() + " - " + productsRealmResults.get(i - 1).getDescription());
item.setProduct(productsRealmResults.get(i - 1));
item.setIdItem(i + "-" + id);
item.setInventory(inventory);
item = realm.copyToRealmOrUpdate(item);
item = realm.copyToRealmOrUpdate(item);
inventoryItems.add(item);
}
inventory.setListItems(inventoryItems);
realm.copyToRealmOrUpdate(inventory);
realm.commitTransaction();
I already looked trough some answers here like this one:
stack answer
and the Java-examples (person, dog, cat)
provided with the API
but I can't understand how to properly insert this.
The problem is that you are setting a list of InventoryItem elements which are not added to the Realm database.
Change InventoryItem item = new InventoryItem(); to InventoryItem item = realm.createObject(InventoryItem.class);
Also, the inventoryItems themselves aren't stored in Realm db. Add realm.copyToRealmOrUpdate(inventoryItems) after the loop.
I am pretty new to Hibernate and JPA implementation in Spring, so basically have set up a MySQL 5 database which maps to the domain objects below.
I am trying to search for Location on the Company_Details table but I can't figure out how to search the class Product_Details for Product_Name at the same time
If anyone could help that would be great.
Company_Details
#Entity
public class Company_Details implements Serializable{
/**
*
*/
private static final long serialVersionUID = 3336251433829975771L;
#Id
#GeneratedValue
private Integer Id;
private String Company;
private String Address_Line_1;
private String Address_Line_2;
private String Postcode;
private String County;
private String Country;
private String Mobile_Number;
private String Telephone_Number;
private String URL;
private String Contact;
private String Logo_URL;
private double Amount_Overall;
private double Amount_Paid;
private Timestamp Date_Joined;
private int Account_Details;
#OneToMany(fetch = FetchType.EAGER, mappedBy = "Company_Id")
private List<Product_Details> products;
public Integer getId() {
return Id;
}
public void setId(Integer id) {
Id = id;
}
public String getCompany() {
return Company;
}
public void setCompany(String company) {
Company = company;
}
public String getAddress_Line_1() {
return Address_Line_1;
}
public void setAddress_Line_1(String address_Line_1) {
Address_Line_1 = address_Line_1;
}
public String getAddress_Line_2() {
return Address_Line_2;
}
public void setAddress_Line_2(String address_Line_2) {
Address_Line_2 = address_Line_2;
}
public String getPostcode() {
return Postcode;
}
public void setPostcode(String postcode) {
Postcode = postcode;
}
public String getCounty() {
return County;
}
public void setCounty(String county) {
County = county;
}
public String getCountry() {
return Country;
}
public void setCountry(String country) {
Country = country;
}
public String getMobile_Number() {
return Mobile_Number;
}
public void setMobile_Number(String mobile_Number) {
Mobile_Number = mobile_Number;
}
public String getTelephone_Number() {
return Telephone_Number;
}
public void setTelephone_Number(String telephone_Number) {
Telephone_Number = telephone_Number;
}
public String getURL() {
return URL;
}
public void setURL(String uRL) {
URL = uRL;
}
public String getContact() {
return Contact;
}
public void setContact(String contact) {
Contact = contact;
}
public String getLogo_URL() {
return Logo_URL;
}
public void setLogo_URL(String logo_URL) {
Logo_URL = logo_URL;
}
public double getAmount_Overall() {
return Amount_Overall;
}
public void setAmount_Overall(double amount_Overall) {
Amount_Overall = amount_Overall;
}
public double getAmount_Paid() {
return Amount_Paid;
}
public void setAmount_Paid(double amount_Paid) {
Amount_Paid = amount_Paid;
}
public Timestamp getDate_Joined() {
return Date_Joined;
}
public void setDate_Joined(Timestamp date_Joined) {
Date_Joined = date_Joined;
}
public int getAccount_Details() {
return Account_Details;
}
public void setAccount_Details(int account_Details) {
Account_Details = account_Details;
}
public List<Product_Details> getProducts() {
return products;
}
public void setProducts(List<Product_Details> products) {
this.products = products;
}
Product_Details
#Entity
public class Product_Details implements Serializable{
/**
*
*/
private static final long serialVersionUID = 6477618197240654478L;
#Id
#GeneratedValue
private Integer Id;
private Integer Company_Id;
private String Product_Name;
private String Description;
private String Main_Photo_URL;
private String Other_Photo_URLS;
private Integer Total_Bookings;
private double Average_Rating;
private Integer Number_Of_Slots;
private Integer Time_Per_Slot;
private double Price_Per_Slot;
private String Monday_Open;
private String Tuesday_Open;
private String Wednesday_Open;
private String Thursday_Open;
private String Friday_Open;
private String Saturday_Open;
private String Sunday_Open;
private String Dates_Closed;
public Integer getId() {
return Id;
}
public void setId(Integer id) {
Id = id;
}
public Integer getCompany_Id() {
return Company_Id;
}
public void setCompany_Id(Integer company_Id) {
Company_Id = company_Id;
}
public String getProduct_Name() {
return Product_Name;
}
public void setProduct_Name(String product_Name) {
Product_Name = product_Name;
}
public String getDescription() {
return Description;
}
public void setDescription(String description) {
Description = description;
}
public String getMain_Photo_URL() {
return Main_Photo_URL;
}
public void setMain_Photo_URL(String main_Photo_URL) {
Main_Photo_URL = main_Photo_URL;
}
public String getOther_Photos_URLS() {
return Other_Photo_URLS;
}
public void setOther_Photos_URLS(String other_Photo_URLS) {
Other_Photo_URLS = other_Photo_URLS;
}
public Integer getTotal_Bookings() {
return Total_Bookings;
}
public void setTotal_Bookings(Integer total_Bookings) {
Total_Bookings = total_Bookings;
}
public double getAverage_Rating() {
return Average_Rating;
}
public void setAverage_Rating(double average_Rating) {
Average_Rating = average_Rating;
}
public Integer getNumber_Of_Slots() {
return Number_Of_Slots;
}
public void setNumber_Of_Slots(Integer number_Of_Slots) {
Number_Of_Slots = number_Of_Slots;
}
public Integer getTime_Per_Slot() {
return Time_Per_Slot;
}
public void setTime_Per_Slot(Integer time_Per_Slot) {
Time_Per_Slot = time_Per_Slot;
}
public double getPrice_Per_Slot() {
return Price_Per_Slot;
}
public void setPrice_Per_Slot(double price_Per_Slot) {
Price_Per_Slot = price_Per_Slot;
}
public String getMonday_Open() {
return Monday_Open;
}
public void setMonday_Open(String monday_Open) {
Monday_Open = monday_Open;
}
public String getTuesday_Open() {
return Tuesday_Open;
}
public void setTuesday_Open(String tuesday_Open) {
Tuesday_Open = tuesday_Open;
}
public String getWednesday_Open() {
return Wednesday_Open;
}
public void setWednesday_Open(String wednesday_Open) {
Wednesday_Open = wednesday_Open;
}
public String getThursday_Open() {
return Thursday_Open;
}
public void setThursday_Open(String thursday_Open) {
Thursday_Open = thursday_Open;
}
public String getFriday_Open() {
return Friday_Open;
}
public void setFriday_Open(String friday_Open) {
Friday_Open = friday_Open;
}
public String getSaturday_Open() {
return Saturday_Open;
}
public void setSaturday_Open(String saturday_Open) {
Saturday_Open = saturday_Open;
}
public String getSunday_Open() {
return Sunday_Open;
}
public void setSunday_Open(String sunday_Open) {
Sunday_Open = sunday_Open;
}
public String getDates_Closed() {
return Dates_Closed;
}
public void setDates_Closed(String dates_Closed) {
Dates_Closed = dates_Closed;
}
}
#Service
public class ProductServiceImpl implements ProductService{
private final static Logger LOG = Logger.getLogger(ProductServiceImpl.class.getName());
#PersistenceContext
EntityManager em;
#Transactional
public List<Company_Details> search(Search search) {
LOG.info("Entering search method");
CriteriaBuilder builder = em.getCriteriaBuilder();
CriteriaQuery<Company_Details> c = builder.createQuery(Company_Details.class);
Root<Company_Details> companyRoot = c.from(Company_Details.class);
c.select(companyRoot);
c.where(builder.equal(companyRoot.get("County"),search.getLocation()));
return em.createQuery(c).getResultList();
}
}
You need two criteria: criteria on the Company_Details class
And criteria on the Product_Details class
Then
Criteria crit1 = session.createCriteria(Company_Details.class);
crit1.add(restriction)
Criteria crit2 = crit1.createCriteria("products");
crit2.add(restriction)
// Then query crit1
List results = crit1.list();