Reputation: 51
With the Persistence provider Hibernate, how to limit entity number using entity
Assume we have an Address
entity, how to limit we can only have 10 addresses for a user?
I want to restrict this on entity level.
Upvotes: 2
Views: 540
Reputation: 12817
annotate the maximum number of children objects allowed using @Size
annotation
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
@Size(max = 2)
private List<Child> children;
If the children exceeded the limit, it will throw below Exception
during persist time
Caused by: javax.validation.ConstraintViolationException: Validation failed for classes [org.myapp.Parent] during persist time for groups [javax.validation.groups.Default, ]
List of constraint violations:[
ConstraintViolationImpl{interpolatedMessage='size must be between 0 and 2', propertyPath=childs, rootBeanClass=class org.myapp.Parent, messageTemplate='{javax.validation.constraints.Size.message}'}
]
also you can specify the min
number of objects.
need to include below dependency in pom if hibernate is used
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>{hibernate.version}</version>
</dependency>
Upvotes: 2
Reputation:
if you are using mysql this might help you for backend(database).
ALTER TABLE tbl_name MAX_ROWS=1000000000 AVG_ROW_LENGTH=nnn;
for front end
List<entity> list=new ArrayList<entity>();
if(list.size()>10){
//some condtions
}
this way you can set the limit table rows
Upvotes: 0