I'm using JPA with Hibernate, on my project i have a UI with so much options from filter on SQL, it's like a Profile to search, the user choose options and choose a nickname from this Profile and save on BD.
But i think not a good idea map/entity Class just for a save filter, then i thought, why i don't save the JPQL/SQL on String column on BD, and retrive when user can use this?
I try use Criteria for it, but can't extract JPQL from this, how i can use criteria, or better for this issue?
A little example:
#SuppressWarnings("unchecked")
public List<Empresa> filtrados(FilterEmpresa filtro) {
Session session = manager.unwrap(Session.class);
Criteria criteria = session.createCriteria(Empresa.class);
if (StringUtils.isNotBlank(filtro.getCodigo())) {
try {
Long longCodigo = Long.parseLong(filtro.getCodigo());
criteria.add(Restrictions.eq("id", longCodigo));
} catch (NumberFormatException ex) {
}
}
if (StringUtils.isNotBlank(filtro.getNome())) {
criteria.add(Restrictions.ilike("nome", filtro.getNome(),
MatchMode.START));
}
if (StringUtils.isNotBlank(filtro.getNomeResumido())) {
criteria.add(Restrictions.ilike("nomeResumido",
filtro.getNomeResumido(), MatchMode.START));
}
return criteria.addOrder(Order.asc("nome")).list();
}
And FilterEmpresa.class:
public class FilterEmpresa implements Serializable {
private static final long serialVersionUID = 1L;
private String codigo;
private String nome;
private String nomeResumido;
public String getCodigo() {
return codigo;
}
public void setCodigo(String codigo) {
this.codigo = codigo;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public String getNomeResumido() {
return nomeResumido;
}
public void setNomeResumido(String nomeResumido) {
this.nomeResumido = nomeResumido;
}
}
Thanks for help.
Related
Hello Stack overflow,
I have the following Problem:
I have these entity classes:
public class UnknownEntity extends NetworkEntity{
#Id
#GeneratedValue(strategy = UuidStrategy.class)
private String id;
#Override
public void setId(String id) {
this.id = id;
}
#Override
public String getId() {
return id;
}
}
#NodeEntity
public class NetworkEntity {
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
#Id
protected String id;
public List<NetworkInterfaceEntity> getInterfaces() {
return interfaces;
}
public void setInterfaces(List<NetworkInterfaceEntity> interfaces) {
this.interfaces = interfaces;
}
#Relationship(type = "is_composed_of")
protected List<NetworkInterfaceEntity> interfaces ;
}
#NodeEntity
public class NetworkInterfaceEntity {
public String getInterfaceId() {
return interfaceId;
}
public void setInterfaceId(String interfaceId) {
this.interfaceId = interfaceId;
}
public String getIpAddress() {
return ipAddress;
}
public void setIpAddress(String ipAddress) {
this.ipAddress = ipAddress;
}
public String getNetmask() {
return netmask;
}
public void setNetmask(String netmask) {
this.netmask = netmask;
}
public String getMacAddress() {
return macAddress;
}
public void setMacAddress(String macAddress) {
this.macAddress = macAddress;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public InterfaceState getState() {
return state;
}
public void setState(InterfaceState state) {
this.state = state;
}
public List<NetworkInterfaceEntity> getSubInterfaces() {
return subInterfaces;
}
public void setSubInterfaces(List<NetworkInterfaceEntity> subInterfaces) {
this.subInterfaces = subInterfaces;
}
public long getBytesSent() {
return bytesSent;
}
public void setBytesSent(long bytesSent) {
this.bytesSent = bytesSent;
}
public long getBytesRecived() {
return bytesRecived;
}
public void setBytesRecived(long bytesRecived) {
this.bytesRecived = bytesRecived;
}
#Id
private String interfaceId;
private String ipAddress;
private String netmask;
private String macAddress;
private String name;
private InterfaceState state;
#Relationship(type = "is_composed_of")
private List<NetworkInterfaceEntity> subInterfaces;
private long bytesSent;
private long bytesRecived;
}
When I now try to query the UnknownEntities via a Neo4j Crud Repository with a custom #Query Method, the UnknownEntities wont be nested with the necessary NetworkInterfaceObjects, even tough my query returns these.
public interface UnknownEntityRepository extends CrudRepository<UnknownEntity,String> {
#Query("MATCH (u:UnknownEntity)-[:is_composed_of]->(i:NetworkInterfaceEntity) WHERE i.ipAddress IN {0} WITH u as unknown MATCH p=(unknown)-[r*0..1]-() RETURN collect(unknown),nodes(p),rels(p)")
List<UnknownEntity> searchMachinesByIp(List<String> ipAddresses);
}
In this particular case the NetworkInterfaceEntities do not contain more subInterfaces, so I only want the NetworkInterfaceEntities that belong the the UnknownEntity. But when I use this Query I only get UnknownEntities where the NetworkInterfaceList is null. I even tried different Querys to no avail for example:
"MATCH p=(u:UnknownEntitie)-[:is_composed_of]-(n:NetworkInterfaceEntity) WHERE n.ipAddress in {0} RETURN collect(n),nodes(p),rels(p)".
My Question is, if what I want is even possible with SDN4 Data and if it is, how I can achieve this, Since my alternative is to query the database for every NetworkInterface separately, which I think is really ugly.
Any help would be much appreciated.
please try if returning the full path like this:
public interface UnknownEntityRepository extends CrudRepository<UnknownEntity,String> {
#Query("MATCH (u:UnknownEntity)-[:is_composed_of]->(i:NetworkInterfaceEntity) WHERE i.ipAddress IN {0} WITH u as unknown MATCH p=(unknown)-[r*0..1]-() RETURN p")
List<UnknownEntity> searchMachinesByIp(List<String> ipAddresses);
}
works for your. If not, try naming the objects in question, i.e. RETURN i as subInterfaces works for you.
Are you using Spring Data Neo4j 4 or 5? If you're on 4, consider the upgrade to 5 to be on a supported level.
Please let me know, if this helps.
I am using Spring Boot/MVC.
I have a custom query using JpaRepository:
public interface WorkOrderRepository extends JpaRepository<WorkOrder, Integer> {
#Query(value = "SELECT * FROM (SELECT * FROM workorder) Sub1 INNER JOIN (SELECT wo_number, GROUP_CONCAT(service_type SEPARATOR ', ') AS 'service_types' FROM service_type GROUP BY wo_number) Sub2 ON Sub1.wo_number=Sub2.wo_number WHERE fleet_company_id=?1 AND (order_status='On-Bidding' OR order_status='Draft')", nativeQuery = true)
Collection<WorkOrder> findWorkOrdersByFleet(Long fleetCompanyID);
}
It returns the following table:
http://imgur.com/Ylkc6U0
As you can see it has service_types columns which is a result of Concat, it's not part of the entity class. My problem is how can I get the value of that column. Some said I can use a separate DTO to map the service_types column? Or I can use 'new' keyword? Maybe you have other worked on me. I also tried to make a transient column service_types but it didn't work.
This is my entity class:
#Entity
#Table(name="workorder")
public class WorkOrder {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name="wo_number")
private Long woNumber;
#ManyToOne(optional=false, cascade=CascadeType.ALL)
#JoinColumn(name = "vehicle_id")
private Vehicle vehicle;
#ManyToOne(optional=false, cascade=CascadeType.ALL)
#JoinColumn(name = "fleet_company_id")
private FleetCompany fleetCompany;
#Column(name="order_title")
private String orderTitle;
#Column(name="order_date")
private String orderDate;
#Column(name="order_time")
private String orderTime;
#Column(name="order_status")
private String orderStatus;
#Column(name="ref_number")
private String refNumber;
#Column(name="proposals")
private int proposals;
//#Column(name="serviceTypes")
#Transient
private int serviceTypes;
public WorkOrder() {
super();
}
public Long getWoNumber() {
return woNumber;
}
public void setWoNumber(Long woNumber) {
this.woNumber = woNumber;
}
public String getOrderTitle() {
return orderTitle;
}
public void setOrderTitle(String orderTitle) {
this.orderTitle = orderTitle;
}
public String getOrderDate() {
return orderDate;
}
public void setOrderDate(String orderDate) {
this.orderDate = orderDate;
}
public String getOrderTime() {
return orderTime;
}
public void setOrderTime(String orderTime) {
this.orderTime = orderTime;
}
public String getOrderStatus() {
return orderStatus;
}
public void setOrderStatus(String orderStatus) {
this.orderStatus = orderStatus;
}
public String getRefNumber() {
return refNumber;
}
public void setRefNumber(String refNumber) {
this.refNumber = refNumber;
}
public int getProposals() {
return proposals;
}
public void setProposals(int proposals) {
this.proposals = proposals;
}
public Vehicle getVehicle() {
return vehicle;
}
public void setVehicle(Vehicle vehicle) {
this.vehicle = vehicle;
}
public FleetCompany getFleetCompany() {
return fleetCompany;
}
public void setFleetCompany(FleetCompany fleetCompany) {
this.fleetCompany = fleetCompany;
}
public int getServiceTypes() {
return serviceTypes;
}
public void setServiceTypes(int serviceTypes) {
this.serviceTypes = serviceTypes;
}
}
Some people told me to make a DTO:
public class WorkOrderDTO extends WorkOrder {
private String service_types;
public WorkOrderDTO() {
super();
}
public WorkOrderDTO(String service_types) {
this.service_types = service_types;
}
public String getService_types() {
return service_types;
}
public void setService_types(String service_types) {
this.service_types = service_types;
}
}
and add make the repository replaced from WorkOrder to WorkOrderDTO.
public interface WorkOrderRepository extends JpaRepository<WorkOrderDTO, Integer>
but when I do that I have autowiring problems.
I solved my own problem, finally!!!
I used #SqlResultMapping
SqlResultSetMapping(
name="workorder",
classes={
#ConstructorResult(
targetClass=WorkOrderDTO.class,
columns={
#ColumnResult(name="wo_number", type = Long.class),
#ColumnResult(name="service_types", type = String.class),
#ColumnResult(name="order_title", type = String.class)
}
)
}
)
And I created a new POJO that is not an entity named WorkOrderDTO.
#PersistenceContext
private EntityManager em;
#Override
public Collection<WorkOrderDTO> getWork() {
Query query = em.createNativeQuery(
"SELECT Sub1.wo_number, Sub2.service_types, Sub1.order_title FROM (SELECT * FROM workorder) Sub1 INNER JOIN (SELECT wo_number, GROUP_CONCAT(service_type SEPARATOR ', ') AS 'service_types' FROM service_type GROUP BY wo_number) Sub2 ON Sub1.wo_number=Sub2.wo_number WHERE fleet_company_id=4 AND (order_status='On-Bidding' OR order_status='Draft')", "workorder");
#SuppressWarnings("unchecked")
Collection<WorkOrderDTO> dto = query.getResultList();
Iterable<WorkOrderDTO> itr = dto;
return (Collection<WorkOrderDTO>)itr;
}
At last, the users who hated me for posting the same problem won't be annoyed anymore.
We recently ran across a bug in our software due to a missing #Id annotation:
#Entity
#Table (name ="PATRONQRSPLANS")
//#IdClass(PatronPlan.class) <-- this was missing
public class Balance {
#Transient
private String kind;
#Transient
private String planName;
#Transient
private PlanCategory planCategory;
#Id
#Column(name="PATRONID")
private int patronId;
//#Id <--- and this was missing
#Column(name="PLANID")
private int planId;
#Column(name="BALANCE")
private int balance;
#Column(name="ENDDATE")
private Date expirationDate;
public Balance() {
this.kind = "balance";
}
public Balance(int balance, int planId, Date expirationDate) {
this.balance = balance;
this.planId = planId;
this.expirationDate = expirationDate;
this.kind = "balance";
}
public int getPatronId() {
return patronId;
}
public void setPatronId(int patronId) {
this.patronId = patronId;
}
public int getBalance() {
return balance;
}
public void setBalance(int balance) {
this.balance = balance;
}
public int getPlanId() {
return planId;
}
public void setPlanId(int planId) {
this.planId = planId;
}
public String getPlanName() {
return planName;
}
public void setPlanName(String planName) {
this.planName = planName;
}
public String getKind() {
return kind;
}
public void setKind(String kind) {
this.kind = kind;
}
public Date getExpirationDate() {
return expirationDate;
}
public void setExpirationDate(Date expirationDate) {
this.expirationDate = expirationDate;
}
public PlanCategory getPlanCategory() {
return planCategory;
}
public void setPlanCategory(PlanCategory planCategory) {
this.planCategory = planCategory;
}
}
The problem is that the table has a primary key constraint on both planId and patronId, so I need a composite key. The query below (without the commented out annotations above), for a patron that has 2 different plans, will return 2 copies of the same plan instead of 2 different ones.
public List<Balance> getBalancesByPatronId(int patronId) {
CriteriaBuilder builder = getEntityManager().getCriteriaBuilder();
CriteriaQuery<Balance> query = builder.createQuery(Balance.class);
Root<Balance> s = query.from(Balance.class);
query.select(s);
query.where(builder.equal(s.get("patronId"), patronId));
return entityManager.createQuery(query).getResultList();
}
To remedy this, I added an #Id and #IdClass annotation as commented out above, as well as creating this class:
public class PatronPlan implements Serializable {
private static final long serialVersionUID = -3518083815234439123L;
#Id
#Column(name="PATRONID")
private int patronId;
#Id
#Column(name="PLANID")
private int planId;
public int getPatronId() {
return patronId;
}
public void setPatronId(int patronId) {
this.patronId = patronId;
}
public int getPlanId() {
return planId;
}
public void setPlanId(int planId) {
this.planId = planId;
}
#Override
public boolean equals(Object obj) {
if (obj == null) return false;
if (!this.getClass().isAssignableFrom(obj.getClass())) return false;
PatronPlan other = (PatronPlan) obj;
return Objects.equals(patronId, other.getPatronId()) && Objects.equals(planId, other.getPlanId());
}
#Override
public int hashCode() {
return Objects.hash(patronId, planId);
}
}
But now I get a NullPointerException in my critera query on the statement
s.get("patronId"), because patronId is not showing up as a declaredAttribute, though it does seem to be showing up in the id information.
Is my composite key setup correct and how to I query for part of a composite key using the criteria api?
If it wasn't clear above, the goal is to be able to get all the Balance objects with a given patronId, even though patronId is only part of the composite key.
I am not certain if this is correct, but it seems to be working. Is this correct? My knowledge of hibernate is limited.
public List<Balance> getBalancesByPatronId(int patronId) {
CriteriaBuilder builder = getEntityManager().getCriteriaBuilder();
CriteriaQuery<Balance> query = builder.createQuery(Balance.class);
Metamodel metaModel = getEntityManager().getMetamodel();
SingularAttribute<Balance, Integer> patronIdAttr =
(SingularAttribute<Balance, Integer>) metaModel.entity(Balance.class)
.getIdClassAttributes().toArray()[0];
Root<Balance> s = query.from(Balance.class);
query.select(s);
query.where(builder.equal(s.get(patronIdAttr), patronId));
return entityManager.createQuery(query).getResultList();
}
How to get values from getter and setter methods in java to insert into Mongodb.I used the below code to insert in to mongodb
DBCollection coll = db.getCollection("mycol");
BasicDBObject doc = new BasicDBObject("id","Hello" ).
append("description", "database").
append("likes", 100).
append("url", "http://http://www.flowersofindia.net/").
append("by", "Rose");
coll.insert(doc);
The above given are some Hard code values.But i need to take the values from setter method thet i have wrote.This is my getter and setter class.
public class Encapsulation {
private String id;
private String product_name;
private String product_url;
private String product_image;
private String product_price;
private String product_src;
private String country;
private String date;
private String Category;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getProduct_name() {
return product_name;
}
public void setProduct_name(String product_name) {
this.product_name = product_name;
}
public String getProduct_url() {
return product_url;
}
public void setProduct_url(String product_url) {
this.product_url = product_url;
}
public String getProduct_image() {
return product_image;
}
public void setProduct_image(String product_image) {
this.product_image = product_image;
}
public String getProduct_price() {
return product_price;
}
public void setProduct_price(String product_price) {
this.product_price = product_price;
}
public String getProduct_src() {
return product_src;
}
public void setProduct_src(String product_src) {
this.product_src = product_src;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getCategory() {
return Category;
}
public void setCategory(String category) {
Category = category;
}
}
.Can anybody help?
Any help will be highly appreciated.I am new to this enviornment
Below is the code to insert into mongodb using setters and getters.
Note that
1) I have used the same Encapsulation class with getters and setters.
2) I have used mongo-java-driver-2.12.2.jar as mongo java driver.
3) mongodb is running at port 27017.
Code:
import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.MongoClient;
public class MongoInsert {
/**
* #param args
* #throws Exception
*/
public static void main(String[] args) throws Exception {
Encapsulation bean=new Encapsulation();
// Setting values
bean.setId("value1");
bean.setProduct_name("value2");
bean.setProduct_image("value3");
bean.setProduct_price("value4");
bean.setProduct_src("value5");
bean.setProduct_url("value6");
bean.setDate("value7");
bean.setCountry("value8");
bean.setCategory("value9");
MongoClient mongo = new MongoClient("localhost", 27017);
DB db = mongo.getDB("Test");
DBCollection coll = db.getCollection("mycol");
//getting values and assigning to mongo field
BasicDBObject doc = new BasicDBObject("id", bean.getId()).
append("Product_name", bean.getProduct_name()).
append("Product_image", bean.getProduct_image()).
append("Product_price", bean.getProduct_price()).
append("Product_src", bean.getProduct_src()).
append("Product_url", bean.getProduct_url()).
append("Date", bean.getDate()).
append("Country", bean.getCountry()).
append("Category", bean.getCategory());
coll.insert(doc);
}
}
Hope it helps.
You want to map your POJO with MongoDB database. you can use ORM for that purpose. You can achieve CRUD and query operations easily in SQL manner using Kundera. Kundera is a JPA 2.1 compliant object-datastore mapping library for NoSQL datastores. You can find more about Kundera on below mentioned link.
https://github.com/impetus-opensource/Kundera/wiki
Hope that Helps...:)
I have entity class "User" as shown below but its not generating primary key. I am using JPA in my app engine application and using app engine endpoints in my android client.
Enitty class:
#Entity
public class UserMaster {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long userId;
private String userName;
private String fullName;
private String userAvtarUrl;
private String userAbout;
private String userGender;
public String getUserName() {
return userName;
}
public Long getUserId() {
return userId;
}
public void setUserId(Long userId) {
this.userId = userId;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getFullName() {
return fullName;
}
public void setFullName(String fullName) {
this.fullName = fullName;
}
public String getUserAvtarUrl() {
return userAvtarUrl;
}
public void setUserAvtarUrl(String userAvtarUrl) {
this.userAvtarUrl = userAvtarUrl;
}
public String getUserAbout() {
return userAbout;
}
public void setUserAbout(String userAbout) {
this.userAbout = userAbout;
}
public String getUserGender() {
return userGender;
}
public void setUserGender(String userGender) {
this.userGender = userGender;
}
}
Endpoint persistence code :
#ApiMethod(name = "insertUserMaster")
public UserMaster insertUserMaster(UserMaster usermaster) {
EntityManager mgr = getEntityManager();
try {
if (containsUserMaster(usermaster)) {
throw new EntityExistsException("Object already exists");
}
mgr.persist(usermaster);
} finally {
mgr.close();
}
return usermaster;
}
Android client
Userendpoint.Builder builder = new Userendpoint.Builder(
AndroidHttp.newCompatibleTransport(),
new JacksonFactory(), new HttpRequestInitializer() {
public void initialize(HttpRequest httpRequest) {
}
});
Userendpoint endpoint = CloudEndpointUtils.updateBuilder(
builder).build();
User objUser = new User();
objUser.setUserName(txtName.getText().toString());
objUser.setUserEmail(txtEmail.getText().toString());
Bitmap bmp = BitmapFactory.decodeFile(imagePath);
ByteArrayOutputStream out = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.PNG, 100, out);
byte[] imgByte = out.toByteArray();
String encodedImage = Base64.encodeToString(imgByte,
Base64.DEFAULT);
objUser.setImage(encodedImage);
User result = endpoint.insertUser(objUser).execute();
Please guide me where i am lacking. Thank you.
If using JPA and GAE/Datastore either use all JPA annotations, or all as a vendor-extension use all JDO annotations. You cannot mix and match.
May be your database server does not provide the auto id generation.
IDENTITY
IDENTITY, it is depend on the Database to auto generate.
Some DB Server Like, MySQL or Microsoft SQL Server do provide ID generation for the primary key field during insertion.
The common way is to use the IdGeneratorStrategy.TABLE. It is not depend on DB.
In my case problem was in method "containsUserMaster(usermaster)"
Method check existing in way like this:
UserMaster item = mgr.find(UserMaster.class, userId);
Problem that until add operation not complete, userId will be null, and because program stops with NullPointerExeption..
I'm add userId checkinq on null - and this solves the problem