Broadleaf : Unable to save Custom Entity - broadleaf-commerce

Hi I Have created a custom entity and how can i save the custom entity to database is there any methods to save the custom entity please help me to solve the issue
Thanks In Advance

Broadleaf has tutorials on how to create your own entity here. I assume that you are now trying to persist this entity. In this case, you should create a Spring component that has #Transactional on it:
#Service
public class MyCustomEntityService {
#PersistenceContext(unitName = "blPU")
private EntityManager em;
#Transactional
public CustomEntity save(CustomEntity ce) {
return em.merge(ce);
}
}
You can also add Spring Data to your project, create a custom repository extending from Spring Data's CrudRepository and use methods there.

Related

Spring Reactive Cassandra, use custom CqlSession

How do we use a custom CqlSession on a Spring Webflux application combined with Spring starter reactive Cassandra please?
I am currently doing the following, which is working perfectly:
public class BaseCassandraConfiguration extends AbstractReactiveCassandraConfiguration {
#Bean
#NonNull
#Override
public CqlSessionFactoryBean cassandraSession() {
final CqlSessionFactoryBean cqlSessionFactoryBean = new CqlSessionFactoryBean();
cqlSessionFactoryBean.setContactPoints(contactPoints);
cqlSessionFactoryBean.setKeyspaceName(keyspace);
cqlSessionFactoryBean.setLocalDatacenter(datacenter);
cqlSessionFactoryBean.setPort(port);
cqlSessionFactoryBean.setUsername(username);
cqlSessionFactoryBean.setPassword(passPhrase);
return cqlSessionFactoryBean;
}
However, I would like to use a custom session, something like:
CqlSession session = CqlSession.builder().build();
How do we tell this configuration to use it?
Thank you
Option 1:
If you are looking to completely override the auto configured CqlSession bean, you can do so by providing your own CqlSesson bean ie.
#Bean
public CqlSession cassandraSession() {
return CqlSession.builder().withClientId(MyClientId).build();
}
The downside of override the entire bean is that you will lose the ability to configure this session via application properties and you will lose the defaults spring boot ships with.
Option 2:
If you want to leave the default values provided by spring boot and have the ability to configure the session via application properties you can use CqlSessionBuilderCustomizer to provide specific custom configurations to the CqlSession. This can be achieved by defining a bean of that type ie:
#Bean
public CqlSessionBuilderCustomizer myCustomiser() {
return cqlSessionBuilder -> cqlSessionBuilder.withClientId(MyClientId);;
}
My personal preference is option 2 as it maintains the functionality provided by spring boot which in my opinion results in an easier to maintain application over time.

Use SAP Cloud SDK to integrate with a custom backend service (oData) based on VDM Generator

I followed Alexander Duemont's blog, trying to implement a Java Spring Boot application that consumes Cloud Foundry Destination. The Destination has a custom OData V2 behind it, coming from an On-Premise ERP system. For local dev, when I perform the Maven build, the Integration-Tests module registers failure due to dependency injection
This is part of my Controller
#RestController
#RequestMapping("/resources")
public class ClassificationsController {
private static final Logger logger = CloudLoggerFactory.getLogger(ClassificationsController.class);
private final ClassificationService service;
public ClassificationsController(#Nonnull final ClassificationService service) {
this.service = service;
}
…..
}
The #Nonnull final ClassificationService Service causes org.springframework.beans.factory.UnsatisfiedDependencyException
I cannot use Spring stereotype annotations on generated Service classes (Fluent) to create Beans!
This question is more likely related to Spring Boot configuration.
I'm assuming ClassificationService is an interface and the implementing class exists in the same package.
Please make sure...
... to add the implementing class of ClassificationService to your component scan / test runtime. Feel free to share the integration test code to setup the test environment. Maybe the additional class reference is missing.
... to correctly annotate the respective Application class of your Spring Boot project. For example, assuming your ClassificationService resides in org.example.services.classification, while the rest of your application uses org.example.app. Your basic Application class would look like this, when following the Cloud SDK guide:
#SpringBootApplication
#ComponentScan({"com.sap.cloud.sdk", "org.example.services.classification", "org.example.app"})
#ServletComponentScan({"com.sap.cloud.sdk", "org.example.app"})
public class Application extends SpringBootServletInitializer
{
#Override
protected SpringApplicationBuilder configure( final SpringApplicationBuilder application )
{
return application.sources(Application.class);
}
public static void main( final String[] args )
{
SpringApplication.run(Application.class, args);
}
}
... to annotate the implementing class of ClassificationService with javax.inject.Named. In case you have multiple implementations of the same interface, make sure to give the not-used class a custom (unique) value for the #Named annotation.
... to look for exceptions (Class not found) in the application log during startup.

Using MVC5 Repository pattern but need advice on where to put business logic

My latest MVC solution consists of an MVC5 site and a DAL class library that will contain a repository interface and class for each entity. I am trying to figure out where to place business logic for my entities such as CheckingAccount.Withdrawl or CheckingAccount.Deposit. Any suggestions? Should this be done within the Model folder within the MVC project while all of the repository classes are in my DAL?
Ideally you want to separate your actual business logic from your entities and abstract it away from your database or ORM as much as possible by creating a business logic layer and injecting your repository into your service/business logic layer using an IoC container and dependency injection.
The common approach is to create a separate class library for your business logic layer that remains agnostic of your UI layer (meaning your UI layer could be an MVC front end or even restful web service) and communicates via data transfer objects.
Here is a simple example:
MVC Controller / UI
public class AccountCheckingController : Controller
{
private readonly IAccountService AccountService;
public CheckingAccountController(IAccountService accountService)
{
this.AccountService accountService;
}
[HttpPost]
public ActionResult Deposit(decimal depositAmount)
{
...
DepositReceiptDto depositReceipt = this.accountServive.Deposit(accountId, depositAmount);
...
return new DepositViewModel {
Receipt = depositReceipt
}
}
}
Business Logic Class / Service (stored in a class library such as WebsiteName.Services or Website.BusinessLogic
public class AccountService : IAccountService
{
private readonly IAccountRepository Repository;
public AccountService(IAccountRepository repository)
{
this.Repository = repository;
}
public DepositReceiptDto Deposit(int accountId, decimal depositAmount)
{
// Perform actions against your repository/ORM here.
return new DepositReceiptDto {
DepositAmount = depositAmount,
User = UserDto,
Status = Status.Success
};
}
...
}
As you can see, by using this separation you can easily switch out your UI without having to perform much work.
I hope this helps.
If something is not an entity and is not a value object, then it's a service. Correct namespace for service depends on his level. Data-access services may be located in the Project.Dal or Project.Dal.Services. The good namespace for domain's service is the Project.Domain.Services.

JSF application backend architecture with JPA and CDI

I'm working on a JSF application with JPA and CDI; I use the following backend architecture:
Controllers (CDI annotation for JSF process)
Services (CDI annotations to be injected into Controllers and other Services)
DAOs (handled with EntityManager)
My question is, how should exactly be EntityManager and transactions be handled?
For example transactions (I don't use EJB or Deltaspike, so no declarative transactions available) should be managed by the Service layer (am I right?), but each data-releated other operation should be handled by the DAOs. So where should EntityManager be injected?
Also, should EntityManager be request (or session or method) scoped?
Thanks,
krisy
I would use service layer to manage a business logic and data access layer to manage object-relational model. As a consequence of the above, entity manager and transactions should be part of DAO. It's important to keep transactions as short as possible.
The decision which type of scope to choose is not so obvious as it depends on the nature of your bean/application. An example usage followed by this presentation, slide #15:
#RequestScoped: DTO/Models, JSF backing beans
#ConversationScoped: multi-step workflow, Shopping cart
#SessionScoped: User login credentials
#ApplicationScoped: Data shared by entire app, Cache
As you can see a scope of a given bean and the related entity manager is specific for the problem it concerns. If a given bean is request scoped its state is preserved for a single HTTP request in the same HTTP session. For a session scoped bean the state is maintained through HTTP session. An example approach may look somehow like the following (pseudocode):
#SessionScoped // conversation, application scoped as well
public class ServiceImpl implements Service {
#Inject
private Dao dao;
public void createSomething(SomeDto dto) {
// dto -> entity transformation
dao.create(entity);
}
public SomeDto getSomething(int id) {
SomeEntity entity = em.findById(id);
// entity -> dto transformation
return dto;
}
}
#RequestScoped
#Transactional
public class DaoImpl implements Dao {
#Inject
private EntityManager em; //creating em is cheap
// TxType.REQUIRED by default
public void create(SomeEntity entity) {
em.persist(entity);
}
#Transactional(TxType.NOT_SUPPORTED)
public SomeEntity findById(int id) {
return em.find(SomeEntity.class, id);
}
}

What is the most concise way to get an injected bean for a springboot managed class?

I have a simple application that injects another component
#ComponentScan
#EnableAutoConfiguration
#Configuration
class Application {
static void main(String[] args) {
SpringApplication.run(Application, args)
}
#Bean
AuthorizationServerTokenServices tokenServices() {
return MY THING HERE
}
}
I'd like a quick/minimal way to new this up and grab the item springboot wires up (for tokenServices in this example). I'm trying to get at this to verify some configuration/settings/etc using TestNG
I should also say that I"m not using any xml to configure this (using gradle/groovy/springboot)
You can easily introduce conditional bean with the help of Spring profiles.
In your case the code would look like:
#Configuration
#Profile("tokenService")
public TestTokenServiceConfig {
#Primary
#Bean
AuthorizationServerTokenServices tokenServices() {
//implementation
}
}
The custom implementation you supply in this class will only be used by Spring in case the profile tokenService is active. The use of #Primary is needed in order to make Spring use the specified bean instead of any others present in the application context.
Also note that since you are going to be using the custom service in a test environment, you could easily mock the implementation using Mockito (or whatever other mocking framework you prefer)
And the actual integration test would be something like:
#RunWith(SpringJUnit4ClassRunner.class)
#SpringApplicationConfiguration(classes = Application.class)
#ActiveProfiles("tokenService")
class YourIntegrationTest {
#Autowired
AuthorizationServerTokenServices tokenServices;
//test
}

Resources