I would like to get objects ResponsableEntity by id from the Database where they are saved. I use Spring-boot and hibernate for the first time and the slouches on other topics don't work in my project
Here are my code :
ResponsableEntity :
#Entity
#Table(name = "responsable")
public class ResponsableEntity {
/**
* Id of the responsable
*/
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
/**
* First name of the responsable
*/
#Column(nullable=false)
private String firstName;
/**
* Lst name of the responsable
*/
#Column(nullable=false)
private String lastName;
/**
* Last latitude of the responsable position
*/
private Double latitude;
/**
* Last longitude of the responsable position
*/
private Double longitude;
/**
* All getters and setters [...]
*/
}
ResponsableDBRepository :
#Repository
public interface ResponsableDBRepository extends CrudRepository<ResponsableEntity, Long> {
}
ResponsableController (REST) :
#RestController
#RequestMapping("/responsable")
public class ResponsableController {
/**
* CRUD Repository atribut needed for the methods below
*/
private final ResponsableDBRepository responsableDBRepository;
private final ResponsableStatDBRepository responsableStatDBRepository;
/**
* Constructor
*
* #param responsableDBRepository CRUD repository for ResponsableEntity
* #param responsableStatDBRepository CRUD repository for ResponsableStatEntity
*/
#Autowired
public ResponsableController(ResponsableDBRepository responsableDBRepository, ResponsableStatDBRepository responsableStatDBRepository){
this.responsableDBRepository = responsableDBRepository;
this.responsableStatDBRepository = responsableStatDBRepository;
}
#GetMapping(path = "/get")
public #ResponseBody String getAllResponsable(){
//get object with id given
return "Returned";
}
}
I'd like that when we call this request, the entity is load from the database and an object ResponsableEntity is created with the infos saved in the database. I already tried most of the answer I found on other topics but most of the time my IDE told me he can't find the class required and it seems to be "default" classes from Hibernate and Spring
Thank you in advance for your answer !
Use this:-
ResponsableEntity responsableEntity = responsableDBRepository.findById(id);
Related
I need to save the id of User and the id of Application in the database to keep track of the changes. I've tried the ModelMapper but it doesn't work and when i try to save the DTO data in the DB I've this error: java.lang.IllegalArgumentException: Unknown entity: it.progettogestionale.dto.generic.LogFileAppDTO
My Entity
#Entity
#Table(name = "logfileapp")
public class LogFileApp implements Serializable{
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer idLogApp;
#Column(name = "data")
private LocalDateTime data;
#Column(name = "nodoconsole")
private Integer nodoConsole;
#Column(name = "launchingmeetingdatagatheringstarting")
private Time launchingMeetingDataGatheringStarting;
#Column(name = "avganalysistime")
private BigDecimal avgAnalysisTime;
#Column(name = "automationenablingdate")
private Date automationEnablingDate;
#Column(name = "done")
private Boolean done;
#Column(name="idpreupdate")
private Integer idPreUpdate;
#Column
private String nome_App, apmCode, insertedInCastProgram, stakeholderEngagement,
stakeholderBrief, onBoardingKitDelivery, primaRestitution, ownerOnboarding, ownerAFP,
gdsUnit, tecnologia, serverManager,
soloCMS, macchina, noteOnboarding, fase, afpStatus, pubblicatoDashboard, noteAppOwner,
jiraautomationActivation,
repoAvailability, automationStatus, automationNotes, greenItIndex,
onboardingKitClosing, sourceCodeFinalDelivery,
linkConfluence, businessCriticality, devMethodology, provider;
#ManyToOne(cascade = CascadeType.ALL , fetch = FetchType.LAZY)
#JoinColumn(name = "FK_idUtente")
private Utente utente;
#ManyToOne(cascade = CascadeType.ALL , fetch = FetchType.LAZY)
#JoinColumn(name = "FK_idApp")
private Applicazione applicazione;
My DTO
public class LogFileAppDTO {
private Integer idLogApp;
private LocalDateTime data;
private Integer nodoConsole;
private Time launchingMeetingDataGatheringStarting;
private BigDecimal avgAnalysisTime;
private Date automationEnablingDate;
private Boolean done;
private Integer idPreUpdate;
private String nome_App, apmCode, insertedInCastProgram, stakeholderEngagement, stakeholderBrief,
onBoardingKitDelivery, primaRestitution, ownerOnboarding, ownerAFP, gdsUnit, tecnologia, serverManager,
soloCMS, macchina, noteOnboarding, fase, afpStatus, pubblicatoDashboard, noteAppOwner,
jiraautomationActivation, repoAvailability, automationStatus, automationNotes, greenItIndex,
onboardingKitClosing, sourceCodeFinalDelivery, linkConfluence, businessCriticality, devMethodology,
provider;
private Integer idUtente;
private Integer idApplicazione;
public LogFileAppDTO() {
}
public LogFileAppDTO(LogFileApp l) {
super();
idLogApp = l.getIdLogApp();
data = l.getData();
nodoConsole = l.getNodoConsole();
launchingMeetingDataGatheringStarting = l.getLaunchingMeetingDataGatheringStarting();
avgAnalysisTime = l.getAvgAnalysisTime();
automationEnablingDate = l.getAutomationEnablingDate();
done = l.getDone();
idPreUpdate = l.getIdPreUpdate();
nome_App = l.getNome_App();
apmCode = l.getApmCode();
insertedInCastProgram = l.getInsertedInCastProgram();
stakeholderEngagement = l.getStakeholderEngagement();
stakeholderBrief = l.getStakeholderBrief();
onBoardingKitDelivery = l.getOnBoardingKitDelivery();
primaRestitution = l.getPrimaRestitution();
ownerOnboarding = l.getOwnerOnboarding();
ownerAFP = l.getOwnerAFP();
gdsUnit = l.getGdsUnit();
tecnologia = l.getTecnologia();
serverManager = l.getServerManager();
soloCMS = l.getSoloCMS();
macchina = l.getMacchina();
noteOnboarding = l.getNoteOnboarding();
fase = l.getFase();
afpStatus = l.getAfpStatus();
pubblicatoDashboard = l.getPubblicatoDashboard();
noteAppOwner = l.getNoteAppOwner();
jiraautomationActivation = l.getJiraautomationActivation();
repoAvailability = l.getRepoAvailability();
automationStatus = l.getAutomationStatus();
automationNotes = l.getAutomationNotes();
greenItIndex = l.getGreenItIndex();
onboardingKitClosing = l.getOnboardingKitClosing();
sourceCodeFinalDelivery = l.getSourceCodeFinalDelivery();
linkConfluence = l.getLinkConfluence();
businessCriticality = l.getBusinessCriticality();
devMethodology = l.getDevMethodology();
provider = l.getProvider();
idUtente = l.getUtente().getIdUtente();
idApplicazione = l.getApplicazione().getIdApplicazione();
}
I have three entities, when modifying one of them I need for my DTO the id of the modified entity and the id of the modifier user. But I can't get it into the database because my entity wants the object while the dto wants the ids.
For DTO <--> Entity conversion you can use:
ModelMapper
MapStruct
implement the interface Converter<S, T> and etc.
You can't save DTO in DB beacuse it's not an Entity class.
But I can't get it into the database because my entity wants the
object while the dto wants the ids.
You can change Ids to DTOs.
Simple example:
public class LogFileApp {
private Utente utente;
}
public class LogFileAppDTO {
private UtenteDTO utente;
}
If you want map nested objects with ID, so you can use deep mappings.
See this article for more information:
https://www.baeldung.com/java-modelmapper
If you want to use ModelMapper you can make work easier with additional methods. Something like:
Service:
public interface MapperService {
/**
* Note: outClass object must have default constructor with no arguments
*
* #param <D> type of result object.
* #param <T> type of source object to map from.
* #param entity entity that needs to be mapped.
* #param outClass class of result object.
* #return new object of <code>outClass</code> type.
*/
<D, T> D map(T entity, Class<D> outClass);
/**
* Note: outClass object must have default constructor with no arguments
*
* #param entityList list of entities that needs to be mapped
* #param outCLass class of result list element
* #param <D> type of objects in result list
* #param <T> type of entity in <code>entityList</code>
* #return list of mapped object with <code><D></code> type.
*/
<D, T> List<D> mapAll(Collection<T> entityList, Class<D> outCLass);
/**
* Maps {#code source} to {#code destination}.
*
* #param source object to map from
* #param destination object to map to
*/
<S, D> D map(S source, D destination);
}
Service implementation
#Service
#RequiredArgsConstructor
public class MapperServiceImpl implements MapperService {
private final ModelMapper modelMapper;
/**
* Note: outClass object must have default constructor with no arguments
*
* #param <D> type of result object.
* #param <T> type of source object to map from.
* #param entity entity that needs to be mapped.
* #param outClass class of result object.
* #return new object of <code>outClass</code> type.
*/
public <D, T> D map(final T entity, Class<D> outClass) {
return modelMapper.map(entity, outClass);
}
/**
* Note: outClass object must have default constructor with no arguments
*
* #param entityList list of entities that needs to be mapped
* #param outCLass class of result list element
* #param <D> type of objects in result list
* #param <T> type of entity in <code>entityList</code>
* #return list of mapped object with <code><D></code> type.
*/
public <D, T> List<D> mapAll(final Collection<T> entityList, Class<D> outCLass) {
return entityList.stream().map(entity -> map(entity, outCLass)).collect(Collectors.toList());
}
/**
* Maps {#code source} to {#code destination}.
*
* #param source object to map from
* #param destination object to map to
*/
public <S, D> D map(final S source, D destination) {
modelMapper.map(source, destination);
return destination;
}
}
I've project with spring, spring-boot and JPA.
When a user tries to log in I want to register activity in a binnacle.
The authentication is with LDAP
I have a new class called LoginActivity and implement an interface with only one method to save activity with annotation #Component and my method where a want to save information when user put credentials wrong I have annotation
#Transactional(propagation = Propagation.REQUIRES_NEW)
And I have another method where I try to save information in my database
I debug my code and it looks good and the process finished well.
But when I saw my database I don't see anything
I use DTO objects between classes
My method authentication:
#Override
#Transactional
public Authentication authenticate(Authentication authentication) {
String name = authentication.getName();
String password = authentication.getCredentials().toString();
List<GrantedAuthority> authorities = (List<GrantedAuthority>) authentication.getAuthorities();
...
context = connect(user, password);//where authentication did
My DTO class, I use lombok
#Data
#Builder
public class LoginDTO {
private String user;
private String tracking;
private Map<String, Boolean> roles;
private String name;
private String lastName;
private boolean loginSuccess;
private String ipAddress;
}
I set every value in my class DTO
LoginDTO loginDTO = LoginDTO.builder()
.loginSuccess(true)
.tracking(tracking)
.lastName(lastName)
.name(name)
.roles(roles)
.user(user)
.ipAddress(httpServletRequest.getRemoteAddr())
.build();
loginActivity.saveLoginActivity(LoginDTO);
My interface
#FunctionalInterface
public interface LoginActivity {
public void saveLoginActivity(LoginDTO loginDTO);
}
My class than implement interface
#Component
#Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public class LoginActivityImpl implements LoginActivity {
My entity
#Entity(name = "activity_desk_control")
#Setter
#Getter
public class ActivityDeskControlEntity {
#Id
#GeneratedValue(generator = "uuid")
#GenericGenerator(name = "uuid", strategy = "uuid2")
#Basic(optional = false)
#Size(max = 255)
#Column(name = "id")
private String id;
#ManyToOne
#JoinColumn(name = "id_user_desk")
private DeskUserLogEntity idUserDesk;
#Column(name = "creation_date")
private Date creationDate;
#Column(name = "id_tracking")
private String idTracking;
#ManyToOne
#JoinColumn(name = "id_service_desk_control")
private ServiceDeskControlEntity idServiceDeskControl;
#Column(name = "params")
#Lob
private String params;
#Column(name = "url")
private String url;
#Column(name = "ip_address")
private String ipAddress;
#Column(name = "login_success")
private int loginSuccess;
#Column(name = "logout")
private int logout;
#Column(name = "logout_date")
private Date logoutDate;
}
My method where I save activity if authentication was well
public void saveMultipart(ActivityDeskControlEntity activityDeskControlEntity) {
this.activityDeskControlRepository.save(activityDeskControlEntity);
}
My method where I save activity if authentication was wrong
#Transactional(propagation = Propagation.REQUIRES_NEW)
public SimpleResponse saveMultipartLoginFail(ActivityDeskControlEntity activityDeskControlEntity) {
this.activityDeskControlRepository.save(activityDeskControlEntity);
}
Have you some idea how I can save information if I got an exception in JPA?
I look some links like this but not work.
My database is Oracle 19c
Update 1
The exception I get when I put credentials wrong is
javax.naming.AuthenticationException: [LDAP: error code 49 - Invalid Credentials]
In this scenario I want to save information the login fail.
Update 2
In the scenario that throws an exception is
context = connect(user, password);
For default LDAP throw an exception when user and password are wrong in consequence in this exception I want to save.
Update 3
I saw in documentation says:
Any RuntimeException or Error triggers rollback, and any checked
Exception does not.
When the user put credentials wrong throw an exception that extends RuntimeException
import org.springframework.security.core.AuthenticationException;
/**
* Thrown if an authentication request is rejected because the credentials are invalid.
* For this exception to be thrown, it means the account is neither locked nor disabled.
*
* #author Ben Alex
*/
public class BadCredentialsException extends AuthenticationException {
// ~ Constructors
// ===================================================================================================
/**
* Constructs a <code>BadCredentialsException</code> with the specified message.
*
* #param msg the detail message
*/
public BadCredentialsException(String msg) {
super(msg);
}
/**
* Constructs a <code>BadCredentialsException</code> with the specified message and
* root cause.
*
* #param msg the detail message
* #param t root cause
*/
public BadCredentialsException(String msg, Throwable t) {
super(msg, t);
}
}
/**
* Abstract superclass for all exceptions related to an {#link Authentication} object
* being invalid for whatever reason.
*
* #author Ben Alex
*/
public abstract class AuthenticationException extends RuntimeException {
// ~ Constructors
// ===================================================================================================
/**
* Constructs an {#code AuthenticationException} with the specified message and root
* cause.
*
* #param msg the detail message
* #param t the root cause
*/
public AuthenticationException(String msg, Throwable t) {
super(msg, t);
}
/**
* Constructs an {#code AuthenticationException} with the specified message and no
* root cause.
*
* #param msg the detailed message
*/
public AuthenticationException(String msg) {
super(msg);
}
}
I tried to change type of exception, but I couldn't, why? spring security to expected BadCredentialsException and not my own BadCredentialsException.
Are there any way to achieve that?
The simplest approach would be a try catch statement since the Stacktrace for the exception is missing in your question I ave to guess that your exception is thrown in line
context = connect(user, password);//where authentication did
A solution would then be
try {
context = connect(user, password);//where authentication did
} catch (AuthenticationException e) {
log.error("User could not autheticate");
someRepository.save(CustomErrorObject);
someOtherCustomSaveMethod();
throw e;
}
the error behavior is still the same since the exception is re thrown in the catch statement, but the save code before can be executed.
I'm using Jackson as a Json parser and I'm getting an error:
No suitable constructor found for type ~ can not instantiate from JSON object
So I've tried adding #NoArgsConstructor, but now I'm getting this one:
constructor AccountItem in class AccountItem cannot be applied to given types
Here's my class:
#Getter
#Builder
public class AccountItem {
/**
* Accounti dentifier
*/
private Long accountId;
/**
* Account name
*/
private String accountName;
/**
* Account priority
*/
private int accountPriority;
}
What might be the cause?
Add both #AllArgsConstructor and #NoArgsConstructor annotations to your class
It's known issue from lombok version 1.16.20. https://github.com/rzwitserloot/lombok/issues/1563
You can do this:
#Getter
#Builder
#JsonDeserialize(builder = AccountItem.AccountItemBuilder.class)
public class AccountItem {
/**
* Accounti dentifier
*/
private Long accountId;
/**
* Account name
*/
private String accountName;
/**
* Account priority
*/
private int accountPriority;
#JsonPOJOBuilder(withPrefix = "")
public static final class AccountItemBuilder {
}
}
I would like to link two classes where the consultant have an ID and I would like to send this ID to the customer so a customer will be assigned to the consultant.
I created a class for the consultant with the ID, name and surname and the same for the customer. I am trying to get the ID from the consultant using the code below
Consultant newconsultant = new Consultant(Consultant.getConsultantID());
The consultantID is the id of the consultant in the class consultant.I am stuck and I appreciate any help with any information for this issue.
Consultant code:
public class Consultant extends Person implements Serializable {
public String ConsultantID;
private String Consfirstname;
private String Conslastname;
Consultant(String consultantID) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
/**
* #return the ConsultantID
*/
public String getConsultantID() {
return ConsultantID;
}
/**
* #param ConsultantID the ConsultantID to set
*/
public void setConsultantID(String ConsultantID) {
this.ConsultantID = ConsultantID;
}
/**
* #return the Consfirstname
*/
public String getConsfirstname() {
return Consfirstname;
}
/**
* #param Consfirstname the Consfirstname to set
*/
public void setConsfirstname(String Consfirstname) {
this.Consfirstname = Consfirstname;
}
/**
* #return the Conslastname
*/
public String getConslastname() {
return Conslastname;
}
/**
* #param Conslastname the Conslastname to set
*/
public void setConslastname(String Conslastname) {
this.Conslastname = Conslastname;
}
Customers Code:
public class Customer extends Person implements Serializable {
private String CustomerID;
public String Custfirstname;
public String Custlastname;
private Consultant Consultant;
public String CID;
Consultant newconsultant = new Consultant(Consultant.getConsultantID());
/**
* #return the CustomerID
*/
public String getCustomerID() {
return CustomerID;
}
/**
* #param CustomerID the CustomerID to set
*/
public void setCustomerID(String CustomerID) {
this.CustomerID = CustomerID;
}
/**
* #return the Custfirstname
*/
public String getCustfirstname() {
return Custfirstname;
}
/**
* #param Custfirstname the Custfirstname to set
*/
public void setCustfirstname(String Custfirstname) {
this.Custfirstname = Custfirstname;
}
/**
* #return the Custlastname
*/
public String getCustlastname() {
return Custlastname;
}
/**
* #param Custlastname the Custlastname to set
*/
public void setCustlastname(String Custlastname) {
this.Custlastname = Custlastname;
}
/**
* #return the Consultant
*/
public Consultant getConsultant() {
return Consultant;
}
/**
* #param Consultant the Consultant to set
*/
public void setConsultant(Consultant Consultant) {
this.Consultant = Consultant;
}
/**
* #return the CID
*/
public String getCID() {
return CID;
}
/**
* #param CID the CID to set
*/
public void setCID(String CID) {
this.CID = CID;
}
There are two forms were the consultant and customers details will be inputted.
In your Customer class are using Consultant class incorrectly.
You are trying to access a non-static method in a static way.
It is not clear if you have getter and setter methods then why you are trying to create a Consultant instance saperately. This looks to be incrrect in design perspective
What you can do is:
From a another class say MyApplication you can first set Consultant and using the same object you can pass it to Customer.
Consultant consultant = new Consultant("123");
consultant.setConsultantID("123");
consultant.setConsfirstname("firstname");
consultant.setConslastname("lastname");
Customer customer = new Customer();
customer.setConsultant(consultant);
This way your customer instance will have a reference to a Consultant instance in it with all the details. This is has-a relationship also called as a composition.
You are calling getConsultatntId in a static way. If your variable is not static you should call the method from a instance of the object (instead of the Class name)
That would look like:
Consumer c = new Consumer(1000);
Consultant con = new Consultant(c.getConsumerId());
Note that I'm calling getId from 'c' that is a instance of Consumer.
Firstly, you should make your Consultant constructor public. Secondly, you cannot access a non-static method in a static way, meaning you need to make a public static String getConsultantID() or something like this:
Consultant c = new Consultant("c2418");
Consultant d = new Consultant(c.getConsultantID());
Two things:
1:
To give a customer a consultant id, you would use an instance method instead of a static method:
Consultant james = new Consultant("123");
Customer customer1 = new Customer(james.getConsultantId());
2:
Consider using an Array or List of Customers in the Consultant class. It would seem more appropriate for a consultant to have multiple customers, rather than a single Consultant to Client relationship. In this way, you create a one-to-many relationship between Consultants and Customers.
Customers would have a reference to their Consultant, and Consultants would have a reference to all of their Customers.
public class Consultant extends Person implements Serializable {
public String ConsultantID;
private String Consfirstname;
private String Conslastname;
private ArrayList<Customer> customers;
Consultant(String consultantID) {
customers = new ArrayList();
}
public boolean addCustomer(Customer c){
customers.add(c);
}
//snipped for brevity
}
public class Customer extends Person implements Serializable {
private String CustomerID;
public String Custfirstname;
public String Custlastname;
public String CID;
Customer(Consultant c){
CID = c.getConsultantID();
}
//snipped for brevity
}
When you create the relationship, you'd create the customer first, assign them a consultant, then add the customer to the Consultant.
Consultant kingston = new Consultant("kingston88"); //created elsewhere
Customer jack = new Customer(kingston); //create customer, give id
kingston.add(jack); //assign customer to consultant
Based on an archetype i created a java ee app. There is an included arquillian test that runs fine. it just calls a method on a #Stateless bean that persists an pre-made entity.
now i added some entity with some relations and i wrote a test for them. But on peristing any entity i get
Transaction is required to perform this operation (either use a transaction or extended persistence context)
I think i need to mark the testmethod with #Transactional but it seems not to be in class path.
Manually invoking the transaction on injected EntityManager yields another error.
So how to correctly setup such tests and dependencies.
EDIT As Grzesiek D. suggested here are some details. this is the entity (the one thta links others):
#Entity
public class Booking implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
/**
* internal id.
*/
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "id", updatable = false, nullable = false)
private Long id;
/**
* Used for optimistic locking.
*/
#Version
#Column(name = "version")
private int version;
/**
* A booking must have a project related.
*/
#ManyToOne
#JoinColumn(name = "project_id")
#NotNull
private Project project;
/**
* A booking must have an owner.
*/
#ManyToOne
#JoinColumn(name = "user_id")
#NotNull
private User owner;
/**
* A booking always has a start time.
*/
#Column
#NotNull
private Timestamp start;
/**
* A booking always has an end time.
*/
#Column
#NotNull
private Timestamp end;
/**
*
* #return true if start is befor end. false otherwise (if equal or after end).
*/
#AssertTrue(message = "Start must before end.")
public final boolean isStartBeforeEnd() {
return start.compareTo(end) < 0;
}
/**
* #return the id
*/
public final Long getId() {
return id;
}
/**
* #param id
* the id to set
*/
public final void setId(final Long id) {
this.id = id;
}
/**
* #return the version
*/
public final int getVersion() {
return version;
}
/**
* #param version
* the version to set
*/
public final void setVersion(final int version) {
this.version = version;
}
/**
* #return the project
*/
public final Project getProject() {
return project;
}
/**
* #param project
* the project to set
*/
public final void setProject(final Project project) {
this.project = project;
}
/**
* #return the owner
*/
public final User getOwner() {
return owner;
}
/**
* #param owner
* the owner to set
*/
public final void setOwner(final User owner) {
this.owner = owner;
}
/**
* #return the start
*/
public final Timestamp getStart() {
return start;
}
/**
* #param start
* the start to set
*/
public final void setStart(final Timestamp start) {
this.start = start;
}
/**
* #return the end
*/
public final Timestamp getEnd() {
return end;
}
/**
* #param end
* the end to set
*/
public final void setEnd(final Timestamp end) {
this.end = end;
}
//hashCode, equals, toString omitted here
}
Here is the test:
#RunWith(Arquillian.class)
public class BookingTest {
#Deployment
public static Archive<?> createDeployment() {
return ArquillianContainer.addClasses(Resources.class, Booking.class, Project.class, User.class);
}
#Inject
private EntityManager em;
#Test
public void createBooking() {
Booking booking = new Booking();
booking.setStart(new Timestamp(0));
booking.setEnd(new Timestamp(2));
User user = new User();
user.setName("Klaus");
booking.setOwner(user);
Project project = new Project();
project.setName("theOne");
project.setDescription("blub");
booking.setProject(project);
em.persist(booking);
System.out.println("here");
}
}
And here the exception:
javax.persistence.TransactionRequiredException: JBAS011469: Transaction is required to perform this operation (either use a transaction or extended persistence context)
I know it will work if i create a #Stateless bean and encapsulate the persist there but i want a direct test of entity's validation and i need a playground to evolve the data model.
In order to have transaction support in Arquillian tests you will need to bring in extension which enables this feature. In your case jta dependency should do the job.
<dependency>
<groupId>org.jboss.arquillian.extension</groupId>
<artifactId>arquillian-transaction-jta</artifactId>
<scope>test</scope>
</dependency>
In addition, if you are using JBoss, you will need to provide its JNDI for UserTranscation, so put following section in your arquillian.xml:
<?xml version="1.0" ?>
<arquillian xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://jboss.org/schema/arquillian" xsi:schemaLocation="http://jboss.org/schema/arquillian
http://jboss.org/schema/arquillian/arquillian_1_0.xsd">
<extension qualifier="transaction">
<property name="manager">java:jboss/UserTransaction</property>
</extension>
</arquillian>
This way you can use #Transactional which comes from this extension's API.