How to Call Entity Manager in a Constructor

How to call Entity Manager in a constructor?

You need to make a service for your class and pass the doctrine entity manager as the argument doctrine.orm.entity_manager.Like in services.yml

services:
test.cutom.service:
class: Test\YourBundleName\Yourfoldernameinbundle\Test
#arguments:
arguments: [ @doctrine.orm.entity_manager ]
#entityManager: "@doctrine.orm.entity_manager"

You must import your services.yml in config.yml

imports:
- { resource: "@TestYourBundleName/Resources/config/services.yml" }

Then in your class's constructor get entity manager as argument

use Doctrine\ORM\EntityManager;
Class Test {

protected $em;

public function __construct(EntityManager $entityManager)
{
$this->em = $entityManager;
}
}

Hope this makes sense

Use entity manager in service

Just inject it into the constructor:

use Doctrine\ORM\EntityManagerInterface

class YourService
{
private $em;

public function __construct(EntityManagerInterface $em)
{
$this->em = $em;
}

// ...
}

Thanks to autowiring no extra configuration is required.

How get EntityManager to execute native sql

@UtilityClass

Im guessing this is your problem. Taken from lombok documentation.

A utility class cannot be instantiated. By marking your class with @UtilityClass, lombok will automatically generate a private constructor that throws an exception, flags as error any explicit constructors you add, and marks the class final. If the class is an inner class, the class is also marked static.

My guess here is the following. Spring can only inject beans into spring managed objects. Your class TableGeoJsonGenerator is not a managed bean because spring can't instantiate it.

You need to remove @UtilityClass and add one of the managed bean annotations, like @Service @Controller etc. etc.

When defining jpa properties in application.properties spring boot will automatically create a EntityManager for you with the properties defined.

This can then be @Autowired into any spring managed bean. You need to make your class managed first.

Is there a way to inject EntityManager into a service

Traditionally, you would have created a new service definition in your services.yml file set the entity manager as argument to your constructor

app.the_service:
class: AppBundle\Services\TheService
arguments: ['@doctrine.orm.entity_manager']

More recently, with the release of Symfony 3.3, the default symfony-standard-edition changed their default services.yml file to default to using autowire and add all classes in the AppBundle to be services. This removes the need for adding the custom service and using a type hint in your constructor will automatically inject the right service.

Your service class would then look like the following:

use Doctrine\ORM\EntityManagerInterface;

class TheService
{
private $em;

public function __construct(EntityManagerInterface $em)
{
$this->em = $em;
}

// ...
}

For more information about automatically defining service dependencies, see https://symfony.com/doc/current/service_container/autowiring.html

The new default services.yml configuration file is available here: https://github.com/symfony/symfony-standard/blob/3.3/app/config/services.yml

Symfony2.3 Better way to get EntityManager inside a Controller

If you must have the EntityManager available in your constructor, a good way to get it is injecting it to the constructor.

To do this you must define your controller as a service.

# src/Acme/DemoBundle/Resources/config/services.yml
parameters:
# ...
acme.controller.quazbar.class: Acme\DemoBundle\Controller\QuazBarController

services:
acme.quazbar.controller:
class: "%acme.controller.quazbar.class%"
# inject doctrine to the constructor as an argument
arguments: [ @doctrine.orm.entity_manager ]

Now all you have to do is modify your controller:

use Doctrine\ORM\EntityManager;

/**
* QuazBar controller.
*
*/
class QuazBarController extends Controller
{

public function __construct(EntityManager $em)
{
$this->em = $em;
}
// ...
}

If you do not require the Entity Manager in the constructor, you can simply get it using the Dependency Injection Container from any method in your controller:

$this->getDoctrine()->getManager();

OR

$this->container->get('doctrine')->getManager();

Controller/setter injection is a good choice because you are not coupling your controller implementation to the DI Container.

At the end which one you use is up to your needs.

Jpa unit test - Service - entity manager null

Hello there is 3 issues in your test code.

1 you should remove the EntityManager entityManager from your test constructor to have a runnable test class.

2 if you want to use entityManager inside your test class you should @Autowired it

public class ServiceTest {
@Autowired
private EntityManager entityManager;

3 It's look like you are testing entityManager and not your LocationService
In an unit test you should mock dependencies like entityManager using Mockito

It's seems like you wanted to create an integration test.

The 3 steps of one integration test of a service (exemple with findLocation())

  1. Prepare the data inside a test database
    Create a new location object and save it into database using the entityManager or the testEntityManager.

  2. Execute your findLocation methode on the id
    Don't forget to Autowire your service class.

  3. Verify if the retrieved data is as expected
    Compare the retrieved Location object with the one you've saved.

Here's the code

@RunWith(SpringRunner.class)
@DataJpaTest
@ActiveProfiles("h2")
@Rollback(false)
@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)
public class ServiceTest {
@Autowired
private EntityManager entityManager;
@Autowired
private LocationService locationService;

public ServiceTest() {

}

@Test
public void findLocation() {
//given

Location location = new Location(....);
entityManager.save(location);

//when
Location foundLocation=locationService.getById(location.getId());
//then
assertTrue(foundLocation.isPresent());
assertEquals(foundLocation.get().getName(), "Avenue");
}

If you have any question I'm available to help you.



Related Topics



Leave a reply



Submit