MongoDB and Morphia - Traditionnal id (Long) instead of ObjectId - java

Background:
My REST service project was started up by using Hibernate. I use id (Long) in domain class as part of the identifier in rest url, for example:
http://abc.com/customer-50, where 50 is the Long id.
The Hibernate Annotated class is as below:
public class Customer {
#Id
#GeneratedValue
private Long id;
}
Now I need to migrate our design to Mongodb. The natural choice is using Morphia, which is an entity framework.
Problem:
In Morphia, the id field is ObjectId
#Id private ObjectId id;
This will cause problem because:
1. It is not auto-increment, i.e. http://abc.com/customer-50, http://abc.com/customer-51, http://abc.com/customer-52.
Now it become http://abc.com/customer-4d1b4687a6d5437619000000
I will need to change all the reference classes from long to objectId.
Is it possible to keep the original design (which uses Long id, instead of ObjectId)?
Thanks!

Take a look at https://code.google.com/p/morphia/source/browse/trunk/morphia/src/main/java/com/google/code/morphia/utils/LongIdEntity.java https://github.com/mongodb/morphia/blob/master/morphia/src/test/java/org/mongodb/morphia/utils/LongIdEntity.java (link updated)
https://github.com/MorphiaOrg/morphia/blob/master/morphia/src/test/java/xyz/morphia/utils/LongIdEntity.java (updated again)

Related

Can I use Java 16 record with JPA entity?

I am trying to do something similar like below.
#Entity
#Table(name="Sample")
public record Sample(Integer id, String name) {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name="user_id")
private Integer id;
#Column(name="username")
private String name;
}
However, it gives me error "User declared non-static fields id are not permitted in a record"
and same for name field as well.
Is there a way to use new java feature "record" with JPA annotation?
See the article, Using Records as Projections in JPA by Billy Korando. The following is a brief summary.
Records cannot be Entities
Jakarta Persistence (JPA; formerly Java Persistence API) implementations such as Hibernate depend on features either forbidden or not recommended by the JEP 395: Records spec: no-arg constructors, non-final fields, setters, etc.
➥ So, no, records cannot be used as JPA Entity.
Other uses of records
You can use records with:
CriteriaBuilder
TypedQuery
NativeQuery
Mapping definition
Spring data has some support as well.
See that article linked above for details, and for links to two other articles.

fetching a Key from a class into an another class

Lets say I have a class in which i generate a DB with some keys, now I want to have an other class in which i use for example the "key123" as I named it in the following, how can I do that? Is that possible to just copy&paste the #Basic and public String key123 in that other class? Will that Basic annotation fetch it from the DB into that class? even when they both have different packages?
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic
#XmlAttribute
#XmlID
private Long id;
#Basic
private String someotherKey;
#Basic
public String key123;
You probably need to use the MVC model of development
Class Keys - the DB Table as an object using the #Entity annotation etc
Class KeysDao - The Data Access Object that does all the DB calls keysDao.update(Keys), keysDao.add(Keys), keysDao.get(id) keysDao.getAllKeys() etc.
Class KeyService - this has the Business Logic so you can say in any other class keyService.getKey(id) and get the Key from the DB returned. Then you can get it in any other class you wish.
If you mean get in another table you need to look at SQL table joins and create your query correctly (or create a view in the DB - not a lot of people know but you can update and add using a View meaning you can make one commit with the data as you use in the view and not have to even know the real normalised DB beneath.

JPA / Spring / Delete Entity, type Mismatch (int/long for id)

I have an Entity which uses
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private long id;
and i have a JPA Repository for this Entity. Now i want to delete one of those, but the standard method for that is delete(int i), which can't work because my ID's are not Integers, but Longs. So apart from using int for my IDs, what to do here? Can i specify a custom delete method which uses long, like it works with findbyXX(XX) ?
EDIT:
First of all: Yes i am using Data JPA!
I want to do this:
jparepository.delete(id);
In case id is an Integer:
org.hibernate.TypeMismatchException: Provided id of the wrong type for class com.Entity. Expected: class java.lang.Long, got class java.lang.Integer
In case id is a long:
no method found for delete(long)
So i can either change my ID to int, which i don't want to do, or find a way to get the Repository to work with long. And the question is how
Ok turns out it was just a stupid mistake. So my JPARepository looked like this:
public interface EntityRepository extends JpaRepository<Entity, Integer> {
But Integer represents the type of the Entities ID-Field, which is Long in my case.
So i needed to change to ..JpaRepository<Entity, Long>
If you are using Spring Data JPA, the default delete method is:
void delete(T entity);
Look here:
Spring Data JPA Docs
Also, you it's better to use Long than primitive long, because then you can use more methods when validating:
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
Assuming you are talking about spring data JPA, yes you can specify a custom method if you want to delete by something user-defined, but that isn't necessary for a delete by ID. See the spring docs:
http://docs.spring.io/spring-data/data-commons/docs/current/api/org/springframework/data/repository/CrudRepository.html#delete-ID-
You can delete by a generic ID type that corresponds to the type of your entities' ID (in your case Long). This should work.

Storing same class objects in both Neo4j and MongoDB ssing Spring Data

The real issue is that both tools use #Id types while I can not create that kind of an object stored in both.
class DataBaseClass {
#GraphId #Field("graphId")
Long graphId;
#Indexed(indexName = "mongodb", indexType = IndexType.FULLTEXT)
#Id
String _id; //mongodb id
}
Neo4j #GraphId extend #Id so there is no difference between the two,
at first I thought changing graphId type from Long to String will will do the trick but I get casting exception error.
I also tried to use mongodb #Field annotation with no differ resoults.
In my humble opinion this prevention is bug in the Spring Data framework, that could be spared from Neo4j if the data layer could accept String id with internal casting.
I think I got the issue covered but I would like to check if there is a way to do this after all.

how to insert/retrieve a userDefined Object in DB-MySql?

I want to insert and retrieve a a user defined Object in DB,am using Mysql5.1.
1)What should me the data type for the column(is Blob is the correct answer for this question)
I am using EntityClass to Insert/Get values from the DB.
2)but to how to insert Object in database?
The common way is to translate the object to a table - every field of the object is (toughly) translates to a column of the table. The term for this is object relational mapping. There is plenty of documentation of this on the web (like this) as this is one of the cornerstones of modern day enterprise development.
There are several libraries you can use, and the best is to stick to the standard called JPA - Java Persistence API. The most known libraries (all open source) are
Hibernate
EclipseLink
OpenJPA
Your user defined object will look like this :
#Entity
#Table(name = "some_table")
public class SomeObject implements Serializable {
static final long serialVersionUID = <some value>;
#Id
#GeneratedValue
protected Long id;
#Column
protected String name;
#Column
protected int value;
// default constructor
// getters, setters
// equals, hashCode, toString
// other methods
}

Categories

Resources