DoctrineORM using EntityManager->merge() - doctrine-orm

The description of merge() method at doctrine documentations says:
Merges the state of a detached entity into the persistence context of this EntityManager and returns the managed copy of the entity. The entity passed to merge will not become associated/managed with this EntityManager.
But I saw next code many times:
$entity = $em->getRepository(...)->findOne($id);
if (null === $entity) {
$entity = new Entity();
$em->persist($entity);
} else {
$entity->setGeneratedAt(new \DateTime());
$em->merge($entity);
}
$em->flush();
Why $em->merge($entity) is used? There is not work with returned copy of the $entity and the $entity is already managed without merge() call.

Related

How to manage vector of pointers in C++ where pointer is allocated by Lua

In the simple 2D Game Engine I am working. I want to define and script my entities using Lua and do all the heavy work in C++ (rendering, physics, etc.)
To do this I have basic Entity class:
class Entity {
public:
Entity() {
alive = true;
livingCount++;
}
void destroy() {
alive = false;
}
bool isAlive() { return alive; }
~Entity(){
// Gets called if I manually call delete entity in EntityManager or if I use smart pointers, but causes seg faults in either case
std::cout << "Entity destructor called." << std::endl;
livingCount--;
}
private:
bool alive;
};
And the EntityManager singleton which groups all active Entities and is used in main game loop to refresh, update and render entities in this order, here is the EntityManager class:
class EntityManager {
public:
static EntityManager* Instance() {
if(s_pInstance == 0) {
s_pInstance = new EntityManager();
return s_pInstance;
}
return s_pInstance;
}
// Main game loop goes through these and calls refresh(), then update() and finally render() on each frame
void update(float deltaTime) {
for (auto& e: entities)
e->update(deltaTime);
}
void render(float deltaTime) {
for (auto& e: entities)
e->draw(deltaTime);
}
// This method causes segfault after entity gets destroyed, it doesn't matter if I use raw pointers or smart, I am still getting segfault here
void refresh() {
for (auto& e: entities) {
if (!e->isAlive()) {
entities.erase(std::remove(entities.begin(), entities.end(), e), entities.end());
// Uncommenting this also causes segfault, but if this is commented, Entity* is not freed from the memory, only gets removed from vector
// delete e;
}
}
// Tried doing the same using shared_ptr or even unique_ptr, but every time entity is destroyed this causes segfault as well
// entities.erase(std::remove_if(std::begin(entities), std::end(entities),
// [](std::shared_ptr<Entity> &e) {
// return !e->isAlive();
// }),
// std::end(entities));
}
// Add new entity
// This will become legacy, I am only using this to create entities in C++, but soon they will only be created by Lua and passed to this class
Entity* addEntity() {
Entity* entity = new Entity();
entities.push_back(entity);
return entity;
}
// Add existing entity: for lua
// I have a feeling this method is not correct
void addEntity(Entity* entity) {
entities.push_back(entity);
}
const std::vector<Entity*>& getEntities() { return entities; }
private:
EntityManager() {}
static EntityManager* s_pInstance;
// Probably should use std::shared_ptr<Entity> instead
// I tried this on Ubuntu and it does seem to solve memory problem and entities get deleted
// but also getting segfault on Linux and I'm not sure if it's because of this class or
// my use of unique pointers
std::vector<Entity*> entities;
};
Now everytime I want to create new Entity, I can do this from Lua script, because I have implemented __index and __gc metamethods for Entity, so this works perfectly:
testEntity = Entity.create()
testEntity:move(400, 400)
testEntity:scale(2, 2)
testEntity:addSprite("slime", "assets/sprite/slime.png", 32, 32)
testEntity:addAnimation("default", "0", "4")
testEntity:addCollider("enemy", 48, 48)
print("Slime ID: "..testEntity:id())
And finally, this is Lua binder for then we want to create new entity, notice how I pass pointer to EntityManager as well, because otherwise game will not update it:
int Script::lua_createEntity(lua_State *L) {
Entity* entity = (Entity*)lua_newuserdata(L, sizeof(Entity));
// Placement new operator takes already allocated memory and calls constructor
new (entity) Entity();
// This Entity created in here must be added to EntityManager vector so that game knows about it
EntityManager::Instance()->addEntity(entity);
luaL_getmetatable(L, "EntityMetaTable");
lua_setmetatable(L, -2);
return 1;
}
And this method is bound to __gc metatable, but does not seem to get called at all, I'm not even sure if I want Lua to take care of this:
// Will be called once lua state is closed
int Script::lua_destroyEntity(lua_State *L) {
Entity* entity = (Entity*)lua_touserdata(L, -1);
std::cout << "Lua __gc for Entity called" << std::endl;
entity->destroy();
return 0;
}
Now, let's say I have an Entity which is also a Projectile, every time Projectile goes off screen, I call entity->destroy() on that Projectile and it's member "isAlive" is marked as "false". This is all done in C++, but projectile gets created by Lua script
So on the next frame, EntityManager refresh() method is invoked and that projectile gets removed correctly from the Vector, but if I try to delete it then to free the memory, it causes segfault, otherwise destructor never gets called.
As I said before, I have tried
std::vectorstd::unique_ptr<Entity> and std::vectorstd::shared_ptr<Entity>, but that also causes segfault in EntityManager refresh method, which makes me think something fundamentally is wrong with how I am dealing with Entity lifetime.
__gc metamethod might not even be needed for me, as I want EntityManager to take care of all active Entities in the game, Lua will only be able to tell it which entity have been marked as destroyed and let C++ take care of deleting it.

How to Mock DataSource Dependency Injection Despite Being Accessible via Static Method

I'm using Mockito, DBUnit and HSQLDB to unit test my database code. I'm also writing integration tests of course.
I'm having trouble understanding how to inject a mocked DataSource into the system under test (class I'm testing). The DataSource is used for connection pooling, and therefore other classes can call a static method in the same class in order to retrieve an instance of this DataSource. This means that the DataSource is not injected into any constructors, anywhere, and so my tests don't have any constructors to inject the mocked DataSource into.
I'm getting around this by altering the logic of my real code to check if a private variable is null, and if so then use the injected DataSource (bad design since it's only needed for tests), otherwise it calls the static method to retrieve the connection pool's source (better design).
How do I inject a mocked DataSource into a class that doesn't have a constructor set up to accept it, because it can instead just call the static method to retrieve the dependency?
Class to Test
public DBConnection(DBSource dbSource) { // <--- Constructor only required for test purposes :(
this.dbSource = dbSource;
}
public final void createCompsDB() {
Connection conn = null;
Statement statement = null;
try {
if(dbSource==null){
conn = DBSource.getInstance().getConnection();
}else{
conn = dbSource.getConnection(); /** Likely bad design, since dbSource is only NOT null for tests, so that you can inject the mocked datasource :( */
}
statement = conn.createStatement();
statement.executeUpdate("CREATE DATABASE placesdb");
System.out.println("Database created...");
} catch (SQLException e) {
// ...
}
} finally {
// Close Resources...
}
}
}
Test Class -- Test Passes
public class DBConnectionTest {
final Statement statement = mock(Statement.class);
final Connection connection = mock(Connection.class);
final DBSource dataSource = mock(DBSource.class);
#Before
public void setUp() throws SQLException, IOException, PropertyVetoException {
when(dataSource.getConnection()).thenReturn(connection);
when(connection.createStatement()).thenReturn(statement);
}
#Test
public void testCreateCompDBIfNotAlready() throws Exception {
DBConnection dbConnection = new DBConnection(localDB, dataSource); /** This constructor is only needed for testing :( . How do I avoid it since all the classes I need to test don't require the dependency to be injected? */
dbConnection.createCompsDB();
verify(statement).executeUpdate("CREATE DATABASE PLACES");
}
}
DBSource.java
protected DBSource() throws IOException, SQLException, PropertyVetoException {
ds = new BasicDataSource();
ds.setDriverClassName("org.postgresql.Driver");
ds.setUsername("user");
ds.setPassword("pass");
ds.setUrl("jdbc:postgresql://localhost:5432/placesdb");
}
public static DBSource getInstance() { // <--- Static method means dependent classes don't need to accept injections
if (datasource == null) {
datasource = new DBSource();
return datasource;
} else {
return datasource;
}
}
public Connection getConnection() throws SQLException {
return this.ds.getConnection();
}
}
Mocking of the static class methods may be done with PowerMockito.
The test class should be something like this:
#RunWith(PowerMockRunner.class)
#PrepareForTest(DBSource.class)
public class DBConnectionTest {
#Mock
final Statement statement;
#Mock
final Connection connection;
#Mock
final DBSource dbsource;
#Before
public void setUp() throws SQLException, IOException, PropertyVetoException {
PowerMockito.mockStatic(DBSource.class);
when(DbSource.getInstance()).thenReturn(dbsource);
when(dbsource.getConnection()).thenReturn(connection);
when(connection.createStatement()).thenReturn(statement);
}
#Test
public void testCreateCompDBIfNotAlready() throws Exception {
DBConnection dbConnection = new DBConnection(localDB); // No test-only constructor anymore
dbConnection.createCompsDB();
verify(statement).executeUpdate("CREATE DATABASE PLACES");
}
}
You can read here more about mocking with PowerMock.

Inverse association assignment in Doctrine2

Does Doctrine2 support the ability to update an association when it is changed from the inverse side? And if not out of the box, is there a plugin/extension I can use to cover this behavior?
Here is an example of what I have:
Organization
/**
* #Id
* #Column(type="integer")
*/
protected $id
/**
* #ManyToOne(targetEntity="Organization", inversedBy="children", cascade={"persist"})
* #JoinColumn(name="parent_org_id", referencedColumnName="id")
*/
protected $parent;
/**
* #OneToMany(targetEntity="Organization", mappedBy="parent", cascade={"persist"})
*/
protected $children;
No. Doctrine 2 tracks associations through the owning side and as it tries to have minimal effect on the behavior of your entities, it wouldn't want to add this kind of functionality.
The standard way to track changes on the inverse side is to ensure that they remain in sync by adding logic to your entities that updates the owning side when making changes on the inverse.
In your example, you could have addChild, removeChild and setParent functions that do something like this:
public function addChild(Organization $child)
{
$this->children[] = $child;
$child->setParent($this); // < update the owning side
}
public function removeChild(Organization $child)
{
$this->children->removeElement($child);
$child->setParent(null); // < update the owning side
}
public function setParent(Organization $parent = null)
{
$this->parent = $parent;
}
You can see that now there is a new problem, you must always use the addChild/removeChild functions (i.e. make changes on the inverse side) for the owning side remain in sync (or sync it yourself, as the caller). This leads to you having to create a policy, either callers must always update on the owning side, or the inverse side.
You could make the setParent function update the inverse side also, but you must be very careful as that can easily lead to infinite recursion:
public function addChild(Organization $child)
{
$this->children[] = $child;
// safely update the owning side
if ($child->getParent() != $this) {
$child->setParent($this);
}
}
public function removeChild(Organization $child)
{
$this->children->removeElement($child);
// safely update the owning side
if ($child->getParent() == $this) {
$child->setParent(null);
}
}
public function setParent(Organization $parent = null)
{
$oldParent = $this->parent;
$this->parent = $parent;
// update the inverse side
if ($oldParent) {
$oldParent->removeChild($this); // will not call setParent
}
if ($this->parent) {
$this->parent->addChild($this); // will not call setParent
}
}
Apart from the added complexity, this scheme is not ideal when for example moving lots of children from one parent to another, because removeChild takes linear time, creating a O(n^2) running time for the move.

Calling CMT bean from BMT bean results in "Local transaction already has 1 non-XA Resource"

I have one EJB with Bean-Managed transaction:
#Singleton
#TransactionManagement(TransactionManagementType.BEAN)
public class BmtBean {
#Resource
private DataSource ds1;
#Resource
private SessionContext sessionCtx;
#EJB
private CmtBean cmtBean;
public void callCmtBean() {
Connection conn1 = null;
try {
conn1 = ds1.getConnection();
// create a PreparedStatement and execute a query
// process result set
while(resultSet.next()) {
// map resultSet to an entity
Entity entity = mapResultSetToEntity(resultSet);
sessionCtx.getUserTransaction().begin();
// pass an entity to another EJB,
// that operates on a different JTA data source
cmtBean.call(entity);
sessionCtx.getUserTransaction().commit();
}
} finally {
// release connection
}
}
}
And another bean with container-managed transaction:
#Singleton
#TransactionManagement(TransactionManagementType.CONTAINER)
public class CmtBean {
#PersistenceContext
private EntityManager em;
#TransactionAttribute(TransactionAttributeType.MANDATORY)
public void call(Entity entities) {
//persist passed entities
//em.flush()
//em.clear();
}
}
Calling cmtBean#call doesn't cause TransactionRequiredException, because prior to that I start a UserTransaction. But when em#flush is called, this exception is thrown:
Caused by: javax.resource.spi.ResourceAllocationException: Error in
allocating a connection. Cause: java.lang.IllegalStateException: Local
transaction already has 1 non-XA Resource: cannot add more resources.
After digging some EclipseLink code, I see that when calling em#flush() it attempts to obtain a new connection from dataSource and fails to do so.
Is this a bug or expected behaviour? How can I fix this?
UPDATE:
See the updated code example.
Also, I have to stress, that I do use 2 non-XA JTA data sources. But since the connection in BmtBean is by default set to autocommit, by the time CmtBean is called, the transaction has to be already commited.

Invoke callback in Moq

I have a method that performs an asynchronous service call. I call this class by passing in the callback.
public void GetRights(EventHandler<GetRightsCompletedEventArgs> callback)
{
ServiceClient client = new ServiceClient();
client.GetRightsCompleted += new EventHandler<GetRightsCompletedEventArgs>(callback);
client.GetRightsAsync();
}
GetRights(GetRightsCallback);
I'm creating tests with MSTest, and I've mocked the containing class (IGetRightsProxy) in Moq. How can I invoke the callback when this method is called in the test?
GetRightsForCurrentUserCompletedEventArgs results =
new GetRightsCompletedEventArgs(
new object[] { new ObservableCollection<Right>()}, null, false, null);
Mock<IGetRightsProxy> MockIGetRightsProxy = new Mock<GetRightsProxy>();
One way of doing what I want is to extend the class like this:
class MockGetRightsProxy : IGetRightsProxy
{
public void GetRights(EventHandler<GetRightsCompletedEventArgs> callback)
{
// Create some args here
GetRightsCompletedEventArgs args = new GetRightsCompletedEventArgs(
new object[] { new ObservableCollection<Right>() }, null, false, null);
callback(null, args);
}
}
I was looking for ways to invoke the callback in Moq, but this works, too.
You want to be looking at Moq's Callback() extension on your mock;
Mock<IGetRightsProxy> mock = new Mock<IGetRightsProxy>();
mock.Setup(x => x.GetRights(It.IsAny<EventHandler<GetRightsCompletedEventArgs>>())
.Callback<EventHandler<GetRightsCompletedEventArgs>>(
callback => callback(mock.Object, new GetRightsCompletedEventArgs())
);
When the code under test calls GetRights() on the IGetRightsProxy mock the actual EventHandler<GetRightsCompletedEventArgs> it passes in will subsequently be passed into Moq's Callback() method.
Note: Type inference will work on the generic applied to Callback() but I find in these cases it is a bit more readable to explicitly define the type being passed into the method.