Bulk operations in CassandraRepository for spring-data-cassandra 2.0M1 - spring-data

I have a simple spring-data-cassandra project that tries to insert multiple entities using
<S extends T> Iterable<S> save(Iterable<S> entities)
of the CassandraRepository class.
However when I use version 2.0.0.M1 (works in previous versions), I get the following error,
Exception in thread "main" org.springframework.data.cassandra.mapping.VerifierMappingExceptions: java.util.ArrayList:
- Cassandra entities must be annotated with either #Persistent, #Table, #UserDefinedType or #PrimaryKeyClass
at org.springframework.data.cassandra.mapping.CompositeCassandraPersistentEntityMetadataVerifier$PersistentAnnotationVerifier.verify(CompositeCassandraPersistentEntityMetadataVerifier.java:92)
at org.springframework.data.cassandra.mapping.CompositeCassandraPersistentEntityMetadataVerifier.verify(CompositeCassandraPersistentEntityMetadataVerifier.java:70)
at org.springframework.data.cassandra.mapping.BasicCassandraPersistentEntity.verify(BasicCassandraPersistentEntity.java:160)
at org.springframework.data.mapping.context.AbstractMappingContext.addPersistentEntity(AbstractMappingContext.java:332)
at org.springframework.data.cassandra.mapping.BasicCassandraMappingContext.addPersistentEntity(BasicCassandraMappingContext.java:381)
at org.springframework.data.cassandra.mapping.BasicCassandraMappingContext.addPersistentEntity(BasicCassandraMappingContext.java:65)
at org.springframework.data.mapping.context.AbstractMappingContext.getPersistentEntity(AbstractMappingContext.java:185)
at org.springframework.data.mapping.context.AbstractMappingContext.getPersistentEntity(AbstractMappingContext.java:145)
at org.springframework.data.mapping.context.AbstractMappingContext.getPersistentEntity(AbstractMappingContext.java:70)
at org.springframework.data.cassandra.core.CassandraTemplate.getPersistentEntity(CassandraTemplate.java:427)
at org.springframework.data.cassandra.core.CassandraTemplate.getTableName(CassandraTemplate.java:443)
at org.springframework.data.cassandra.core.CassandraTemplate.insert(CassandraTemplate.java:314)
at org.springframework.data.cassandra.core.CassandraTemplate.insert(CassandraTemplate.java:302)
at org.springframework.data.cassandra.repository.support.SimpleCassandraRepository.save(SimpleCassandraRepository.java:66)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at org.springframework.data.repository.core.support.RepositoryFactorySupport$ImplementationMethodExecutionInterceptor.executeMethodOn(RepositoryFactorySupport.java:553)
at org.springframework.data.repository.core.support.RepositoryFactorySupport$ImplementationMethodExecutionInterceptor.invoke(RepositoryFactorySupport.java:538)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.doInvoke(RepositoryFactorySupport.java:479)
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.invoke(RepositoryFactorySupport.java:460)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.data.projection.DefaultMethodInvokingMethodInterceptor.invoke(DefaultMethodInvokingMethodInterceptor.java:61)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:92)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:213)
at com.sun.proxy.$Proxy34.save(Unknown Source)
My main class, App.java
public class App
{
public static void main(String[] args) {
ApplicationContext context =new AnnotationConfigApplicationContext(CassandraConfig.class);
CustomerRepo repo=context.getBean(CustomerRepo.class);
List<Customer> customers=new ArrayList<Customer>();
Customer cust=new Customer();
cust.SetId("142");
cust.setName("Mayor");
cust.setAcc_type("new");
cust.setAcc_name("savings");
cust.setSegment("Normal");
customers.add(cust);
Customer cust1 = new Customer();
cust1.SetId("143");
cust1.setName("Final");
cust1.setAcc_type("new");
cust1.setAcc_name("savings");
cust1.setSegment("Normal");
customers.add(cust1);
repo.save(customers);
}
}
The entity class, Customer.java
#Table(value="Customer")
public class Customer {
#PrimaryKeyColumn(name = "id",ordinal = 1,type = PrimaryKeyType.PARTITIONED)
private String id;
#Column(value ="name")
private String name;
#Column(value = "acc_name")
private String acc_name;
#Column(value = "acc_type")
private String acc_type;
#Column(value = "segment")
private String segment;
public Customer(String id, String name, String acc_name, String acc_type,
String segment) {
this.id=id;
this.name=name;
this.acc_name=acc_name;
this.acc_type=acc_type;
this.segment=segment;
}
public Customer() {
}
public void SetId(String id)
{
this.id=id;
}
public void setName(String name)
{
this.name=name;
}
public void setAcc_name(String acc_name)
{
this.acc_name=acc_name;
}
public void setAcc_type(String acc_type)
{
this.acc_type=acc_type;
}
public void setSegment(String segment)
{
this.segment=segment;
}
public String getId() {
return id;
}
public String getName() {
return name;
}
public String getAcc_name() {
return acc_name;
}
public String getAcc_type() {
return acc_type;
}
public String getSegment() {
return segment;
}
}
And finally, the repository, CustomerRepo.java
import com.Entity.Customer;
public interface CustomerRepo extends CassandraRepository<Customer> {
}
Is this an issue (I haven't been able to find via Goolge or the site), or am I missing some annotations ?

For batch queries, use CassandraTemplate helps to insert batch of operations with multiple entities. This is available with Spring Data Cassandra.
example code:
CassandraBatchOperations batchOps = cassandraTemplate.batchOps();
batchOps(movieByGenre);
batchOps(movieByActor);
batchOps.insert(movie);
batchOps.execute();
This will use Cassandra native Batch operation internally.

Related

MongoRepository Save method does not insert in database

I have created a SpringBoot project with Jhipster. The database I am using is MongoDB.
In the application-dev.yml I have the following configuration:
data:
mongodb:
uri: mongodb://<user>:<pass>#<ip>:<port>
database: gateway
The user, password, ip Address, and port, in my application-dev are real values.
The DatabaseConfiguration.java is:
#Configuration
#EnableMongoRepositories("es.second.cdti.repository")
#Profile("!" + JHipsterConstants.SPRING_PROFILE_CLOUD)
#Import(value = MongoAutoConfiguration.class)
#EnableMongoAuditing(auditorAwareRef = "springSecurityAuditorAware")
public class DatabaseConfiguration {
private final Logger log = LoggerFactory.getLogger(DatabaseConfiguration.class);
#Bean
public ValidatingMongoEventListener validatingMongoEventListener() {
return new ValidatingMongoEventListener(validator());
}
#Bean
public LocalValidatorFactoryBean validator() {
return new LocalValidatorFactoryBean();
}
#Bean
public MongoCustomConversions customConversions() {
List<Converter<?, ?>> converters = new ArrayList<>();
converters.add(DateToZonedDateTimeConverter.INSTANCE);
converters.add(ZonedDateTimeToDateConverter.INSTANCE);
return new MongoCustomConversions(converters);
}
#Bean
public Mongobee mongobee(MongoClient mongoClient, MongoTemplate mongoTemplate, MongoProperties mongoProperties) {
log.debug("Configuring Mongobee");
Mongobee mongobee = new Mongobee(mongoClient);
mongobee.setDbName(mongoProperties.getMongoClientDatabase());
mongobee.setMongoTemplate(mongoTemplate);
// package to scan for migrations
mongobee.setChangeLogsScanPackage("es.second.cdti.config.dbmigrations");
mongobee.setEnabled(true);
return mongobee;
}}
The CloudDatabaseConfiguration is:
#Configuration
#EnableMongoRepositories("es.second.cdti.repository")
#Profile(JHipsterConstants.SPRING_PROFILE_CLOUD)
public class CloudDatabaseConfiguration extends AbstractCloudConfig {
private final Logger log = LoggerFactory.getLogger(CloudDatabaseConfiguration.class);
#Bean
public MongoDbFactory mongoFactory() {
return connectionFactory().mongoDbFactory();
}
#Bean
public LocalValidatorFactoryBean validator() {
return new LocalValidatorFactoryBean();
}
#Bean
public ValidatingMongoEventListener validatingMongoEventListener() {
return new ValidatingMongoEventListener(validator());
}
#Bean
public MongoCustomConversions customConversions() {
List<Converter<?, ?>> converterList = new ArrayList<>();
converterList.add(DateToZonedDateTimeConverter.INSTANCE);
converterList.add(ZonedDateTimeToDateConverter.INSTANCE);
converterList.add(DurationToLongConverter.INSTANCE);
return new MongoCustomConversions(converterList);
}
#Bean
public Mongobee mongobee(MongoDbFactory mongoDbFactory, MongoTemplate mongoTemplate, Cloud cloud) {
log.debug("Configuring Cloud Mongobee");
List<ServiceInfo> matchingServiceInfos = cloud.getServiceInfos(MongoDbFactory.class);
if (matchingServiceInfos.size() != 1) {
throw new CloudException("No unique service matching MongoDbFactory found. Expected 1, found "
+ matchingServiceInfos.size());
}
MongoServiceInfo info = (MongoServiceInfo) matchingServiceInfos.get(0);
Mongobee mongobee = new Mongobee(info.getUri());
mongobee.setDbName(mongoDbFactory.getDb().getName());
mongobee.setMongoTemplate(mongoTemplate);
// package to scan for migrations
mongobee.setChangeLogsScanPackage("es.second.cdti.config.dbmigrations");
mongobee.setEnabled(true);
return mongobee;
}
}
The cdtiApp.java is:
#SpringBootApplication
#EnableConfigurationProperties({ApplicationProperties.class})
public class CdtiApp implements InitializingBean{
private static final Logger log = LoggerFactory.getLogger(CdtiApp.class);
private final Environment env;
public CdtiApp(Environment env) {
this.env = env;
}
/**
* Initializes cdti.
* <p>
* Spring profiles can be configured with a program argument --spring.profiles.active=your-active-profile
* <p>
* You can find more information on how profiles work with JHipster on https://www.jhipster.tech/profiles/.
*/
#PostConstruct
public void initApplication() {
Collection<String> activeProfiles = Arrays.asList(env.getActiveProfiles());
if (activeProfiles.contains(JHipsterConstants.SPRING_PROFILE_DEVELOPMENT) && activeProfiles.contains(JHipsterConstants.SPRING_PROFILE_PRODUCTION)) {
log.error("You have misconfigured your application! It should not run " +
"with both the 'dev' and 'prod' profiles at the same time.");
}
if (activeProfiles.contains(JHipsterConstants.SPRING_PROFILE_DEVELOPMENT) && activeProfiles.contains(JHipsterConstants.SPRING_PROFILE_CLOUD)) {
log.error("You have misconfigured your application! It should not " +
"run with both the 'dev' and 'cloud' profiles at the same time.");
}
}
/**
* Main method, used to run the application.
*
* #param args the command line arguments.
*/
public static void main(String[] args) {
SpringApplication app = new SpringApplication(CdtiApp.class);
DefaultProfileUtil.addDefaultProfile(app);
Environment env = app.run(args).getEnvironment();
logApplicationStartup(env);
}
private static void logApplicationStartup(Environment env) {
String protocol = "http";
if (env.getProperty("server.ssl.key-store") != null) {
protocol = "https";
}
String serverPort = env.getProperty("server.port");
String contextPath = env.getProperty("server.servlet.context-path");
if (StringUtils.isBlank(contextPath)) {
contextPath = "/";
}
String hostAddress = "localhost";
try {
hostAddress = InetAddress.getLocalHost().getHostAddress();
} catch (UnknownHostException e) {
log.warn("The host name could not be determined, using `localhost` as fallback");
}
log.info("\n----------------------------------------------------------\n\t" +
"Application '{}' is running! Access URLs:\n\t" +
"Local: \t\t{}://localhost:{}{}\n\t" +
"External: \t{}://{}:{}{}\n\t" +
"Profile(s): \t{}\n----------------------------------------------------------",
env.getProperty("spring.application.name"),
protocol,
serverPort,
contextPath,
protocol,
hostAddress,
serverPort,
contextPath,
env.getActiveProfiles());
String configServerStatus = env.getProperty("configserver.status");
if (configServerStatus == null) {
configServerStatus = "Not found or not setup for this application";
}
log.info("\n----------------------------------------------------------\n\t" +
"Config Server: \t{}\n----------------------------------------------------------", configServerStatus);
}
#Override
public void afterPropertiesSet() throws Exception {
// TODO Auto-generated method stub
}
}
The Vehicle entity:
#org.springframework.data.mongodb.core.mapping.Document(collection = "vehicle")
public class Vehicle implements Serializable {
private static final long serialVersionUID = 1L;
#Id
private String id;
#NotNull
#Field("plate")
private String plate;
#NotNull
#Field("registrationDate")
private Instant registrationDate;
#NotNull
#Field("brand")
private String brand;
#NotNull
#Field("model")
private String model;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getPlate() {
return plate;
}
public void setPlate(String plate) {
this.plate = plate;
}
public Instant getRegistrationDate() {
return registrationDate;
}
public void setRegistrationDate(Instant registrationDate) {
this.registrationDate = registrationDate;
}
public String getBrand() {
return brand;
}
public void setBrand(String brand) {
this.brand = brand;
}
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
}
The VehicleDTO is:
public class VehicleDTO {
private String id;
private String plate;
private Instant registrationDate;
private String brand;
private String model;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getPlate() {
return plate;
}
public void setPlate(String plate) {
this.plate = plate;
}
public Instant getRegistrationDate() {
return registrationDate;
}
public void setRegistrationDate(Instant registrationDate) {
this.registrationDate = registrationDate;
}
public String getBrand() {
return brand;
}
public void setBrand(String brand) {
this.brand = brand;
}
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
}
The VehicleMapper is:
#Mapper(componentModel = "spring")
public interface VehicleMapper{
Vehicle toEntity(VehicleDTO source);
VehicleDTO toDto(Vehicle target);
}
The VehicleResource is:
#RestController
#RequestMapping("/api")
#CrossOrigin(origins = "*", methods = { RequestMethod.GET, RequestMethod.POST })
public class VehicleResource {
private final Logger log = LoggerFactory.getLogger(VehicleResource.class);
#Value("${jhipster.clientApp.name}")
private String applicationName;
#Autowired
private final VehicleService vehicleService;
public VehicleResource(VehicleService vehicleService) {
this.vehicleService = vehicleService;
}
#PostMapping("/vehicle")
#PreAuthorize("hasAuthority(\"" + AuthoritiesConstants.ADMIN + "\")")
public ResponseEntity<Vehicle> createVehicle(#Valid #RequestBody VehicleDTO vehicleDTO) throws URISyntaxException {
log.debug("REST request to save Vehicle : {}", vehicleDTO);
Vehicle newVehicle = vehicleService.createVehicle(vehicleDTO);
return ResponseEntity.created(new URI("/api/vehicle/" + newVehicle.getPlate()))
.headers(HeaderUtil.createAlert(applicationName, "vehicleManagement.created", newVehicle.getPlate()))
.body(newVehicle);
}
}
The VehicleService interface is:
public interface VehicleService {
Vehicle createVehicle(VehicleDTO vehicleDTO);
}
The VehicleServiceImpl is:
#Service
public class VehicleServiceImpl implements VehicleService{
#Autowired
private final VehicleRepository vehicleRepository;
#Autowired
private final VehicleMapper mapper;
public VehicleServiceImpl(VehicleRepository vehicleRepository, VehicleMapper mapper) {
this.vehicleRepository = vehicleRepository;
this.mapper = mapper;
}
private final Logger log = LoggerFactory.getLogger(VehicleServiceImpl.class);
#Override
public Vehicle createVehicle(VehicleDTO vehicleDTO) {
Vehicle vehicle = vehicleRepository.save(mapper.toEntity(vehicleDTO));
log.debug("Created Information for vehicle: {}", vehicle);
return vehicle;
}
}
The VehicleRepository interface is:
/**
* Spring Data MongoDB repository for the {#link Vehicle} entity.
*/
#Repository
public interface VehicleRepository extends MongoRepository<Vehicle, String> {
}
From the Swagger console I access the Vehicle-Resource:
Swagger console
Click on the button and write in the text box the json with the vehicle data:
enter JSON data
As we can see in the following image, the answer is 201. Initially the vehicle was saved with the identifier "id": "60e740935ed5a10e2c2ed19e".
Send request
I access the database to check that the vehicle has been correctly stored in the vehicle table. To my surprise ... there is no vehicle in the vehicle table:
show database
I can make sure that the data in the database application-dev is OK. I don't have any other databases.
I suspect that transactions with the database are not actually being made. This data is somehow stored in memory because if I do a findAllVehicles from Swagger it does return the vehicle.
I have a eureka server running (jhipster-registry) and two microservices that synchronize with it. The Gateway, which acts as a reverse proxy and the Vehiculos microservice. The Swagger console is the gateway, from where I make the request to insert vehicles. Everything seems to work, but as I say in bbdd does not save anything.

How to create mock object of such method which return type is List<Tuple>

I am trying to write test case for Account Controller. At very first My I am creating mock object but that methods return type is List<Tuple>. I am not getting how to create mock object of following method which return type is List
Can any one tell me how to create mock object for following method?
AccountController
#GetMapping("/findAccountData")
public ResponseEntity<List<Tuple>> populateGridViews(#RequestParam(value="sClientAcctId",required=false) String sClientAcctId,
#RequestParam(value="sAcctDesc",required=false) String sAcctDesc,
#RequestParam(value="sInvestigatorName",required=false)String sInvestigatorName,
#RequestParam(value="sClientDeptId",required=false) String sClientDeptId) throws Exception {
return ResponseEntity.ok(accService.populateGridViews(sClientAcctId, sAcctDesc,sInvestigatorName,sClientDeptId));
}
AccountService
public List<Tuple> populateGridViews(String sClientAcctId, String sAcctDesc, String sInvestigatorName,
String sClientDeptId)throws Exception{
QAccount account = QAccount.account;
QDepartment department = QDepartment.department;
QAccountCPCMapping accountCPCMapping = QAccountCPCMapping.accountCPCMapping;
QInvestigator investigator = QInvestigator.investigator;
JPAQuery<Tuple> query = new JPAQuery<Tuple>(em);
query.select(Projections.bean(Account.class, account.sClientAcctId, account.sAcctDesc, account.sLocation,
Projections.bean(Department.class, department.sDeptName, department.sClientDeptId).as("department"),
Projections.bean(Investigator.class, investigator.sInvestigatorName).as("investigator"),
Projections.bean(AccountCPCMapping.class, accountCPCMapping.sCCPCode).as("accountCPC"))).from(account)
.innerJoin(account.department, department).innerJoin(account.accountCPC, accountCPCMapping)
.innerJoin(account.investigator, investigator);
if (StringUtils.isNotEmpty(sClientAcctId)) {
query.where(account.sClientAcctId.equalsIgnoreCase(sClientAcctId));
}
// code.......
return query.fetch();
}
AccountControllerTest
#RunWith(SpringRunner.class)
public class TestAccountController {
private MockMvc mockMvc;
#Mock
private AccountService accountService;
#InjectMocks
private AccountController accountController;
#Before
public void setup() {
mockMvc = MockMvcBuilders.standaloneSetup(accountController).build();
}
#Test
public void populateGridViewsTest() throws Exception {
String sClientAcctId = "1122";
String sAcctDesc = "SRI";
String sInvestigatorName = "Ram";
String sClientDeptId = "1200";
Tuple mockedTuple = Mockito.mock(Tuple.class);
List<Tuple> accountObj = new ArrayList<>();
accountObj.add(mockedTuple);
Mockito.when(accountService.populateGridViews(sClientAcctId, sAcctDesc, sInvestigatorName, sClientDeptId))
.thenReturn(accountObj);
mockMvc.perform(
get("/spacestudy/$ InstituteIdentifier/admin/account/findAccountData")
.param("sClientAcctId", "1122")
.param("sAcctDesc", "SRI")
.param("sInvestigatorName", "Ram")
.param("sClientDeptId", "1200")
.accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andDo(print());
Mockito.verify(accountService).populateGridViews(sClientAcctId, sAcctDesc, sInvestigatorName, sClientDeptId);
}
Stack Trace
org.mockito.exceptions.misusing.MissingMethodInvocationException:
when() requires an argument which has to be 'a method call on a mock'.
For example:
when(mock.getArticles()).thenReturn(articles);
Also, this error might show up because:
1. you stub either of: final/private/equals()/hashCode() methods.
Those methods *cannot* be stubbed/verified.
Mocking methods declared on non-public parent classes is not supported.
2. inside when() you don't call method on mock but on some other object.
at com.spacestudy.controller.AccountControllerTest.populateGridViewsTest(AccountControllerTest.java:57)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)
at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:252)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:94)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:191)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:538)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:760)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:460)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:206)
#RunWith(SpringRunner.class)
#SpringBootTest
#AutoConfigureMockMvc
public class TestAccountController {
#Autowired
private MockMvc mockMvc;
#Autowired
private AccountService accountService;
#Autowired
private AccountController accountController;
#Test
#Transactional
public void populateGridViewsTest() throws Exception {
String sClientAcctId = "1122";
String sAcctDesc = "SRI";
String sInvestigatorName = "Ram";
String sClientDeptId = "1200";
Tuple mockedTuple = Mockito.mock(Tuple.class);
List<Tuple> accountObj = new ArrayList<>();
accountObj.add(mockedTuple);
Mockito.when(accountService.populateGridViews(sClientAcctId, sAcctDesc, sInvestigatorName, sClientDeptId))
.thenReturn(accountObj);
mockMvc.perform(
get("/spacestudy/$ InstituteIdentifier/admin/account/findAccountData")
.param("sClientAcctId", "1122")
.param("sAcctDesc", "SRI")
.param("sInvestigatorName", "Ram")
.param("sClientDeptId", "1200")
.accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andDo(print());
Mockito.verify(accountService).populateGridViews(sClientAcctId, sAcctDesc, sInvestigatorName, sClientDeptId);
}
#AutoConfigureMockMvc
public class TickServiceTest {
#Autowired
private MockMvc mockMvc;
}
First you have to try this..instead of using Mockito use MockMvc object. And just tell me u want to create AccountController object or Account bean object?
You can implements Tuple interface and use it in thenReturn method.
import java.util.Arrays;
import com.querydsl.core.Tuple;
import com.querydsl.core.types.Expression;
public class MockedTuple implements Tuple {
private final Object[] a;
public MockedTuple(Object[] a) {
this.a = a;
}
#SuppressWarnings("unchecked")
#Override
public <T> T get(int index, Class<T> type) {
return (T) a[index];
}
#Override
public <T> T get(Expression<T> expr) {
return null;
}
#Override
public int size() {
return a.length;
}
#Override
public Object[] toArray() {
return a;
}
#Override
public boolean equals(Object obj) {
if (obj == this) {
return true;
} else if (obj instanceof Tuple) {
return Arrays.equals(a, ((Tuple) obj).toArray());
} else {
return false;
}
}
#Override
public int hashCode() {
return Arrays.hashCode(a);
}
#Override
public String toString() {
return Arrays.toString(a);
}
}
Example of test:
Object[] myReturnedObject = new Object[1];
myReturnedObject[0] = value;
when(myService.getTuples(...params)).thenReturn(
List.of(new MockedTuple(myReturnedObject))
)

Rest API with Spring Data MongoDB - Repository method not working

I am reading and learning Spring Boot data with MongoDB. I have about 10 records in my database in the following format:
{
"_id" : ObjectId("5910c7fed6df5322243c36cd"),
name: "car"
}
When I open the url:
http://localhost:8090/items
I get an exhaustive list of all items. However, I want to use the methods of MongoRepository such as findById, count etc. When I use them as such:
http://localhost:8090/items/count
http://localhost:8090/items/findById/5910c7fed6df5322243c36cd
http://localhost:8090/items/findById?id=5910c7fed6df5322243c36cd
I get a 404.
My setup is as so:
#SpringBootApplication
public class Application {
public static void main(String[] args) throws IOException {
SpringApplication.run(Application.class, args);
}
}
#Document
public class Item implements Serializable {
private static final long serialVersionUID = -4343106526681673638L;
#Id
private String id;
private String name;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
#RepositoryRestResource(collectionResourceRel = "item", path = "items")
public interface ItemRepository<T, ID extends Serializable> extends MongoRepository<Item, String>, ItemRepositoryCustom {
}
What am I doing wrong? Do I need to implement the methods as defined by MongoRepository or will they be automatically implemented? I am lost and have been trying to figure this out for so long. I do not have any methods in my controller, its empty.
You have to declare the findById method in order for it to be exposed.
Item findById(String id);
Item findByName(String name);
Note that you don't need to implement the methods. SpringBoot will analyse the method name and provide the proper implementation
I had same issue,
After removing #Configuration,#ComponentScan everything worked fine.

Spring Boot store data with WebSockets

I have a simple WebSocket set up and try to save data. Somehow the data gets not persisted. I don't get any error messages and the object gets returned correct to the client. If I try to store the object with a REST controller and a REST request it works.
Here are the dependencies of my build.gradle file:
dependencies {
compile 'org.springframework.boot:spring-boot-starter-web'
compile 'org.springframework.boot:spring-boot-starter-data-jpa'
compile 'org.springframework.boot:spring-boot-starter-websocket'
compile 'org.springframework:spring-messaging'
compile 'com.google.code.gson:gson:1.7.2'
compile 'org.postgresql:postgresql:9.4-1200-jdbc41'
compile 'commons-dbcp:commons-dbcp:1.4'
testCompile('org.springframework.boot:spring-boot-startet-test')
}
PersonController
#Controller
public class PersonController {
#Autowired
PersonRepository personRepository;
#MessageMapping("/test")
#SendTo("/response/test")
public Person test() throws Exception {
Person person = new Person();
person.setName("John Doe");
return personRepository.save(person);
}
}
Configuration for STOMP messaging
#Configuration
#EnableWebSocketMessageBroker
public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer {
#Override
public void configureMessageBroker(MessageBrokerRegistry config) {
config.enableSimpleBroker("/response");
config.setApplicationDestinationPrefixes("/app");
}
#Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/websocket")
.setAllowedOrigins("*")
.withSockJS();
}
Person entity
#Entity
public class Person {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private long id;
private String name;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return getName;
}
public void setName(String name) {
this.name = name;
}
}
Base Repository
#NoRepositoryBean
public interface BaseRepository<T, ID extends Serializable> extends Repository<T, ID> {
void delete(T deleted);
void delete(ID id);
Iterable<T> findAll();
T findOne(ID id);
T save(T persisted);
Iterable<T> save(Iterable<T> persited);
}
Person Repository
public interface PersonRepository extends
BaseRepository<Person, Serializable> {
}
Is there a problem in my code?
Is there an issue with caching? Do I have to force flushing?
Is storing data with WebSockets supported by SpringBoot?
Do you know any examples with storing data? I could only find basic examples without storing data.
The problem was in my persistence configuration. I changed the configuration from a Java implementation to the application.properties file. I think there was a problem with my transaction manager.
To be complete, here is my current application.properties file:
spring.datasource.url = jdbc:postgresql://localhost:5432/test
spring.datasource.username = test
spring.datasource.password = test
spring.datasource.testWhileIdle = true
spring.datasource.validationQuery = SELECT 1
spring.jpa.show-sql = true
spring.jpa.hibernate.ddl-auto = create
spring.jpa.hibernate.naming-strategy = org.hibernate.cfg.ImprovedNamingStrategy
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.PostgreSQLDialect

EntityManager persist() method does not insert record to database => SEVERE: javax.persistence.TransactionRequiredException

I have problem with using EntityManager persist() method.
I am using JSF2.0, glassfish 3, JPA and hibernate, i am not using spring.
I try to add events in an events table with the method persist, but EntityManager persist() method does not insert record to database and i have this error message =>
SEVERE: javax.persistence.TransactionRequiredException
at com.sun.enterprise.container.common.impl.EntityManagerWrapper.doTxRequiredCheck(EntityManagerWrapper.java:163)
at com.sun.enterprise.container.common.impl.EntityManagerWrapper.flush(EntityManagerWrapper.java:411)
at dao.EvenementDao.addEvenement(EvenementDao.java:128).
#ManagedBean
#Stateless
public class EvenementDao implements Serializable{
/**
*
*/
private static final long serialVersionUID = -3343483942392617877L;
/**
*
*/
private List<TEvenement> listeEvenement;
private List<SelectItem> listeSelectItemEvnt;
private TEvenement tevenement ;
public EvenementDao() {
}
#PersistenceUnit(unitName="GA2010-ejbPU-dev")
private EntityManagerFactory emf;
#PostConstruct
private void init() {
tevenement = new TEvenement();
}
public List<TEvenement> getListeEvenement() {
EntityManager em = emf.createEntityManager();
TypedQuery<TEvenement> requete = m.createNamedQuery("TEvenement.findPrivateOther",
TEvenement.class);
listeEvenement = requete.getResultList();
return listeEvenement;
}
public TEvenement getEvenement() {
return tevenement;
}
public void setEvenement(TEvenement evenement) {
this.tevenement = evenement;
}
public void addEvenement(){
EntityManager em = emf.createEntityManager();
HttpSession session = (HttpSession) FacesContext.getCurrentInstance().
getExternalContext().getSession(false);
Integer codeUser = (Integer) session.getAttribute("codeUser");
tevenement.setUtilCreation(codeUser);
System.out.println("je rentre dans addevenemnt");
try{
System.out.println("i persist "+ em);
em.persist(tevenement);
em.flush();
System.out.println(tevenement.getDetailsEvenement());
FacesMessage message = new FacesMessage("Evenement ajouté avec succès.");
FacesContext.getCurrentInstance().addMessage(null, message);
}catch(Exception e){
e.printStackTrace();
}
}
}
So, this is not working, but the progam enter in the fonction addEvenement , FacesMessage message = new FacesMessage("Evenement ajouté avec succès."); returns me the message as if it was working.
i thouht it was due to my entityMAnager but in fact an ohter function works fine with the same Entity manager so i dont understand.
**public List<TEvenement> getListeEvenement()** {
EntityManager em = emf.createEntityManager();
TypedQuery<TEvenement> requete = em.createNamedQuery("TEvenement.findPrivateOther", TEvenement.class);
listeEvenement = requete.getResultList();
return listeEvenement;
}
this one works fine, the only difference is that in this case the query is a select and in the other case it's a persist so a query that impact the database.
the code of the entity :
#Entity
#Table(name="t_evenements")
#NamedQueries({#NamedQuery(name="TEvenement.findAll", query="SELECT evnt FROM TEvenement evnt"),
#NamedQuery(name="TEvenement.findPrivateOther", query="SELECT evnt FROM TEvenement evnt WHERE evnt.typeEvenement = 6 OR evnt.typeEvenement = 7")})
public class TEvenement implements Serializable {
private static final long serialVersionUID = -1908959833491896991L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name="REF_EVENEMENT", unique=true, nullable=false)
private Integer refEvenement;
#Temporal(TemporalType.DATE)
#Column(name="DATE_DEBUT_EVENEMENT")
private Date dateDebutEvenement;
#Temporal(TemporalType.DATE)
#Column(name="DATE_FIN_EVENEMENT")
private Date dateFinEvenement;
#Column(name="DETAILS_EVENEMENT")
private String detailsEvenement;
#Column(name="IS_EVERYDAY")
private byte isEveryday;
#Column(name="RAPPEL_EVENEMENT")
private int rappelEvenement;
public Integer getUtilEvenement() {
return utilEvenement;
}
public void setUtilEvenement(Integer utilEvenement) {
this.utilEvenement = utilEvenement;
}
#Column(name="TITRE_EVENEMENT")
private String titreEvenement;
#Column(name="TYPE_EVENEMENT")
private String typeEvenement;
#Column(name="UTIL_COPIE_EVENEMENT")
private Integer utilCopieEvenement;
#Column(name="UTIL_EVENEMENT")
private Integer utilEvenement;
#Column(name="HEURE_EVENEMENT")
private String heureEvenement;
#Column(name="UTIL_CREATION")
private Integer utilCreation;
public String getHeureEvenement() {
return heureEvenement;
}
public void setHeureEvenement(String heureEvenement) {
this.heureEvenement = heureEvenement;
}
public TEvenement() {
}
public Integer getRefEvenement() {
return this.refEvenement;
}
public void setRefEvenement(int refEvenement) {
this.refEvenement = refEvenement;
}
public Date getDateDebutEvenement() {
return this.dateDebutEvenement;
}
public Integer getUtilCreation() {
return utilCreation;
}
public void setUtilCreation(Integer utilCreation) {
this.utilCreation = utilCreation;
}
public void setUtilCopieEvenement(Integer utilCopieEvenement) {
this.utilCopieEvenement = utilCopieEvenement;
}
public void setDateDebutEvenement(Date dateDebutEvenement) {
this.dateDebutEvenement = dateDebutEvenement;
}
public Date getDateFinEvenement() {
return this.dateFinEvenement;
}
public void setDateFinEvenement(Date dateFinEvenement) {
this.dateFinEvenement = dateFinEvenement;
}
public String getDetailsEvenement() {
return this.detailsEvenement;
}
public void setDetailsEvenement(String detailsEvenement) {
this.detailsEvenement = detailsEvenement;
}
public byte getIsEveryday() {
return this.isEveryday;
}
public void setIsEveryday(byte isEveryday) {
this.isEveryday = isEveryday;
}
public int getRappelEvenement() {
return this.rappelEvenement;
}
public void setRappelEvenement(int rappelEvenement) {
this.rappelEvenement = rappelEvenement;
}
public String getTitreEvenement() {
return this.titreEvenement;
}
public void setTitreEvenement(String titreEvenement) {
this.titreEvenement = titreEvenement;
}
public String getTypeEvenement() {
return this.typeEvenement;
}
public void setTypeEvenement(String typeEvenement) {
this.typeEvenement = typeEvenement;
}
public Integer getUtilCopieEvenement() {
return this.utilCopieEvenement;
}
public void setUtilCopieEvenement(int utilCopieEvenement) {
this.utilCopieEvenement = utilCopieEvenement;
}
}
Do anyone have a idea what am i missing?
The difference isn't that you call persist, the difference is that you call em.flush() which as the error states, requires the EntityManager be joined to a transaction. Makes sure your getListeEvenement() method is wrapped in a transaction, or start one depending on your setup.