ManyToOne Relationship Dont Persist - foreign-keys

When i try persisting the Parent entity, it persist fine but when i try the child Entity, it returns an error.
This is the Parent Entity
#Entity(name="Parent_Detail")
public class Parent implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Column(name = "Parent_ID", nullable = false)
private Integer parent_id;
public Integer getParent_id() {
return parent_id;
}
public void setParent_id(Integer parent_id) {
this.parent_id = parent_id;
}
}
This is the Child Entity
#Entity
public class Child implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Column(name = "Child_ID", nullable = false)
private Integer child_id;
#ManyToOne
private Parent parent;
public Integer getChild_id() {
return child_id;
}
public void setChild_id(Integer child_id) {
this.child_id = child_id;
}
public Parent getParent() {
return parent;
}
public void setParent(Parent parent) {
this.parent = parent;
}
}
This is the session bean for the child
#Stateless
#LocalBean
public class ChildSessionBean {
#PersistenceContext(unitName = "WebApplication4PU")
private EntityManager em;
public void persist(Object object) {
em.persist(object);
}
}
This is the Sesion Bean For the Parent(It works fine)
#Stateless
#LocalBean
public class ParentSessionBean {
#PersistenceContext(unitName = "WebApplication4PU")
private EntityManager em;
public void persist(Object object) {
em.persist(object);
}
}
This is the managed Bean for the child
public class ChildManagedBean {
#EJB
private ChildSessionBean childSessionBean;
private Child child = new Child();
public ChildManagedBean() {
}
public Child getChild() {
return child;
}
public void setChild(Child child) {
this.child = child;
}
public void save(){
child.setParent(new Parent());
childSessionBean.persist(child);
}
}
This is the managedBean For The parent
public class ParentManagedBean {
#EJB
private ParentSessionBean parentSessionBean;
private Parent parent = new Parent();
public ParentManagedBean() {
}
public Parent getParent() {
return parent;
}
public void setParent(Parent parent) {
this.parent = parent;
}
public void save(){
parentSessionBean.persist(parent);
}
}
This is the Child JSF Page: I kept it simple without the dropdown.
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html">
<h:head>
<title>Facelet Title</title>
</h:head>
<h:body>
<h:form>
Child ID :<h:inputText value="#{childManagedBean.child.child_id}" /><br/>
Parent ID :<h:inputText value="#{childManagedBean.child.parent}" /><br/>
<h:commandButton action="#{childManagedBean.save()}" immediate="true"/>
</h:form>
</h:body>
</html>
This is the error Page
javax.faces.el.EvaluationException: javax.ejb.EJBException: Transaction aborted
at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:102)
at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:102)
at javax.faces.component.UICommand.broadcast(UICommand.java:315)
at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:794)
at javax.faces.component.UIViewRoot.processDecodes(UIViewRoot.java:935)
at com.sun.faces.lifecycle.ApplyRequestValuesPhase.execute(ApplyRequestValuesPhase.java:78)
at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:118)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:593)
at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1542)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:281)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:175)
at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:655)
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:595)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:161)
at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:331)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:231)
at com.sun.enterprise.v3.services.impl.ContainerMapper$AdapterCallable.call(ContainerMapper.java:317)
at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:195)
at com.sun.grizzly.http.ProcessorTask.invokeAdapter(ProcessorTask.java:849)
at com.sun.grizzly.http.ProcessorTask.doProcess(ProcessorTask.java:746)
at com.sun.grizzly.http.ProcessorTask.process(ProcessorTask.java:1045)
at com.sun.grizzly.http.DefaultProtocolFilter.execute(DefaultProtocolFilter.java:228)
at com.sun.grizzly.DefaultProtocolChain.executeProtocolFilter(DefaultProtocolChain.java:137)
at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:104)
at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:90)
at com.sun.grizzly.http.HttpProtocolChain.execute(HttpProtocolChain.java:79)
at com.sun.grizzly.ProtocolChainContextTask.doCall(ProtocolChainContextTask.java:54)
at com.sun.grizzly.SelectionKeyContextTask.call(SelectionKeyContextTask.java:59)
at com.sun.grizzly.ContextTask.run(ContextTask.java:71)
at com.sun.grizzly.util.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:532)
at com.sun.grizzly.util.AbstractThreadPool$Worker.run(AbstractThreadPool.java:513)
at java.lang.Thread.run(Thread.java:636)
Caused by: javax.ejb.EJBException: Transaction aborted
at com.sun.ejb.containers.BaseContainer.completeNewTx(BaseContainer.java:5142)
at com.sun.ejb.containers.BaseContainer.postInvokeTx(BaseContainer.java:4901)
at com.sun.ejb.containers.BaseContainer.postInvoke(BaseContainer.java:2045)
at com.sun.ejb.containers.BaseContainer.postInvoke(BaseContainer.java:1994)
at com.sun.ejb.containers.EJBLocalObjectInvocationHandler.invoke(EJBLocalObjectInvocationHandler.java:222)
at com.sun.ejb.containers.EJBLocalObjectInvocationHandlerDelegate.invoke(EJBLocalObjectInvocationHandlerDelegate.java:88)
at $Proxy402.persist(Unknown Source)
at SessionBean.__EJB31_Generated__ChildSessionBean__Intf____Bean__.persist(Unknown Source)
at managedBean.ChildManagedBean.save(ChildManagedBean.java:33)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:616)
at javax.el.BeanELResolver.invokeMethod(BeanELResolver.java:779)
at javax.el.BeanELResolver.invoke(BeanELResolver.java:528)
at javax.el.CompositeELResolver.invoke(CompositeELResolver.java:257)
at com.sun.el.parser.AstValue.invoke(AstValue.java:248)
at com.sun.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:302)
at org.jboss.weld.util.el.ForwardingMethodExpression.invoke(ForwardingMethodExpression.java:39)
at org.jboss.weld.el.WeldMethodExpression.invoke(WeldMethodExpression.java:50)
at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:105)
at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:88)
... 32 more
Caused by: javax.transaction.RollbackException: Transaction marked for rollback.
at com.sun.enterprise.transaction.JavaEETransactionImpl.commit(JavaEETransactionImpl.java:473)
at com.sun.enterprise.transaction.JavaEETransactionManagerSimplified.commit(JavaEETransactionManagerSimplified.java:855)
at com.sun.ejb.containers.BaseContainer.completeNewTx(BaseContainer.java:5136)
... 53 more
Caused by: java.lang.IllegalStateException: During synchronization a new object was found through a relationship that was not marked cascade PERSIST: bean.Parent#13d247e.
at org.eclipse.persistence.internal.sessions.RepeatableWriteUnitOfWork.discoverUnregisteredNewObjects(RepeatableWriteUnitOfWork.java:304)
at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.calculateChanges(UnitOfWorkImpl.java:702)
at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.commitToDatabaseWithChangeSet(UnitOfWorkImpl.java:1490)
at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.issueSQLbeforeCompletion(UnitOfWorkImpl.java:3143)
at org.eclipse.persistence.internal.sessions.RepeatableWriteUnitOfWork.issueSQLbeforeCompletion(RepeatableWriteUnitOfWork.java:346)
at org.eclipse.persistence.transaction.AbstractSynchronizationListener.beforeCompletion(AbstractSynchronizationListener.java:157)
at org.eclipse.persistence.transaction.JTASynchronizationListener.beforeCompletion(JTASynchronizationListener.java:68)
at com.sun.enterprise.transaction.JavaEETransactionImpl.commit(JavaEETransactionImpl.java:435)
... 55 more

The exception message says it all:
During synchronization a new object was found through a relationship that was not marked cascade PERSIST: bean.Parent#13d247e
You're trying to persist a child. And the child's parent is a new Parent. Parent is not persistent. SO you're trying to persist a child with a parent that is not persistent. It can't work.
Either what you want is to save a new child for an existing parent, and then you must attach this existing parent to the child:
Parent existingParent = em.getReference(Parent.class, existingParentId);
Child child = new Child();
child.setParent(existingParent);
em.persist(child);
Or you want to save a new child with a new parent in one go, and you must persist the parent, then the child:
Parent parent = new Parent();
Child child = new Child();
child.setParent(existingParent);
em.persist(parent);
em.persist(child);
Or you want to save a new child with a new parent in one go, and let JPA persist the parent automatically when the child is persisted, and you must then make the persist cascaded
#ManyToOne(cascade = CascadeType.PERSIST)
private Parent parent;
...
Parent parent = new Parent();
Child child = new Child();
child.setParent(existingParent);
em.persist(child);

Related

How to write Unit test for ViewModel that contains RxJava/RxAndroid

I'm trying to refactor one pretty old project, so I started implementing new architecture (MVVM) with Dagger2, RxJava, RxAndroid... Now everything is connected and working fine, now the problem is, I have no idea how to write a Unit test for my ViewModel..
I want to start with Login screen first, so I created a LoginViewModel, but first let me show you what I did..
I have a DataModule that provides 2 classes, RestApiRepository and ViewModelFactory. RestApiRepository looks like this:
public class RestApiRepository {
private RestClient restClient;
public RestApiRepository(RestClient restClient) {
this.restClient = restClient;
}
public Observable<AuthResponseEntity> authenticate(String header, AuthRequestEntity requestEntity) {
return restClient.postAuthObservable(header, requestEntity);
}
}
Rest client with api call for login:
public interface RestClient {
#POST(AUTH_URL)
Observable<AuthResponseEntity> postAuthObservable(#Header("Authorization") String authKey, #Body AuthRequestEntity requestEntity);
}
Second class from DataModule is ViewModelFactory:
#Singleton
public class ViewModelFactory extends ViewModelProvider.NewInstanceFactory implements ViewModelProvider.Factory {
private RestApiRepository repository;
#Inject
public ViewModelFactory(RestApiRepository repository) {
this.repository = repository;
}
#NonNull
#Override
public <T extends ViewModel> T create(#NonNull Class<T> modelClass) {
if (modelClass.isAssignableFrom(LoginViewModel.class)) {
return (T) new LoginViewModel(repository);
}
throw new IllegalArgumentException("Unknown class name");
}
}
And finally, LoginViewModel:
public class LoginViewModel extends ViewModel {
private final CompositeDisposable disposable = new CompositeDisposable();
private final MutableLiveData<AuthResponseEntity> responseLiveData = new MutableLiveData<>();
private RestApiRepository restApiRepository;
private SchedulerProvider provider;
public LoginViewModel(RestApiRepository restApiRepository, SchedulerProvider provider) {
this.restApiRepository = restApiRepository;
this.provider = provider;
}
public MutableLiveData<AuthResponseEntity> getResponseLiveData() {
return responseLiveData;
}
#Override
protected void onCleared() {
disposable.clear();
}
public void auth(String token, AuthRequestEntity requestEntity) {
if (token != null && requestEntity != null) {
disposable.add(restApiRepository.authenticate(token, requestEntity)
.subscribeOn(provider.io())
.observeOn(provider.ui())
.subscribeWith(new DisposableObserver<AuthResponseEntity>() {
#Override
public void onNext(AuthResponseEntity authResponseEntity) {
responseLiveData.setValue(authResponseEntity);
}
#Override
public void onError(Throwable e) {
AuthResponseEntity authResponseEntity = new AuthResponseEntity();
authResponseEntity.setErrorMessage(e.getMessage());
responseLiveData.setValue(authResponseEntity);
}
#Override
public void onComplete() {
}
}
));
}
}
}
So, I'm sure everything is connected well, I can successfuly login...
For the RxAndroid test issues, I found somewhere that I have to use this Scheduler provider like this:
public class AppSchedulerProvider implements SchedulerProvider {
public AppSchedulerProvider() {
}
#Override
public Scheduler computation() {
return Schedulers.trampoline();
}
#Override
public Scheduler io() {
return Schedulers.trampoline();
}
#Override
public Scheduler ui() {
return Schedulers.trampoline();
}
}
Below is my LoginViewModelTest class, but I don't know how to handle RxJava/RxAndroid inside the tests..
#RunWith(MockitoJUnitRunner.class)
public class LoginViewModelTest {
#Mock
private RestApiRepository restApiRepository;
#Mock
private MutableLiveData<AuthResponseEntity> mutableLiveData;
private LoginViewModel loginViewModel;
#Before
public void setUp() {
MockitoAnnotations.initMocks(this);
AppSchedulerProvider schedulerProvider = new AppSchedulerProvider();
loginViewModel = Mockito.spy(new LoginViewModel(restApiRepository, schedulerProvider));
}
#Test
public void authenticate_error() {
String token = "token";
AuthRequestEntity requestEntity = Mockito.mock(AuthRequestEntity.class);
Mockito.doReturn(Observable.error(new Throwable())).when(restApiRepository).authenticate(token, requestEntity);
loginViewModel.auth(token, requestEntity);
AuthResponseEntity responseEntity = Mockito.mock(AuthResponseEntity.class);
responseEntity.setErrorMessage("Error");
Mockito.verify(mutableLiveData).setValue(responseEntity);
}
}
So, I wanted to write a test for failed case when onError is called, but when I run it, I get this error:
exclude patterns:io.reactivex.exceptions.UndeliverableException: The exception could not be delivered to the consumer because it has already canceled/disposed the flow or the exception has nowhere to go to begin with. Further reading: https://github.com/ReactiveX/RxJava/wiki/What's-different-in-2.0#error-handling | java.lang.RuntimeException: Method getMainLooper in android.os.Looper not mocked. See http://g.co/androidstudio/not-mocked for details.
You can mock the behaviour of restApiRepository:
Mockito.when(restApiRepository.authenticate(token, requestEntity)).thenReturn(Observable.error(error));
and verify that responseLiveData.setValue is being called with the appropriate parameters

Moq, unit test using xUnit framework and testing a function returning an object

I have a repository
public class StudentsPersonalDetailsRepository : IStudentPersonalDetailsRepository
{
private readonly StudentManagementSystemEntities _studentsDbContext;
private readonly ILogger _logger;
public StudentsPersonalDetailsRepository(StudentManagementSystemEntities context, ILogger<IStudentPersonalDetailsRepository> logger)
{
_studentsDbContext = context;
_logger = logger;
}
public IQueryable<StudentPersonalDetails> StudentPersonalDetails => _studentsDbContext.StudentPersonalDetails;
......
}
In my Service layer, I am having a service as
public class StudentsPersonalDetailsService:IStudentPersonalDetailsService
{
private readonly IStudentPersonalDetailsRepository _repository;
private readonly ILogger _logger;
public StudentsPersonalDetailsService(IStudentPersonalDetailsRepository studentPersonalDetailsRepository,ILogger<StudentsPersonalDetailsService> logger)
{
_repository = studentPersonalDetailsRepository;
_logger = logger;
}
......
......
public StudentModelResponse GetStudentById(int id)
{
Domain.Entities.StudentPersonalDetails obj = _repository.StudentPersonalDetails.
Where(i => i.RollNo == id)
.Select(i=>new Domain.Entities.StudentPersonalDetails {
RollNo=i.RollNo,
FirstName=i.FirstName,
LastName=i.LastName,
MailId=i.MailId,
MiddleName=i.MiddleName,
DateOfBirth=i.DateOfBirth,
GenderOfPerson=i.GenderOfPerson
}).FirstOrDefault();
StudentModel ob = StudentModel.Translator(obj);
return new StudentModelResponse { StudentModel=ob};
}
}
My Test code is
namespace StudentUnitTests
{
public class StudentServiceShould
{
[Theory]
[InlineData(1)]
public void AbleToRetrieveStudentById(int n)
{
var mock = new Mock<IStudentPersonalDetailsRepository>();
var logger = new Mock<ILogger<StudentsPersonalDetailsService>> ();
var ob = new StudentsPersonalDetailsService(mock.Object, logger.Object);
}
}
}
I need to write a unit test for GetStudentById() and check the values returned by the function.
Please help me to how to mock the service layer.
In the above we have two things happening within StudentsPersonalDetailsService.GetStudentById()
Retrieve the student info from the repository.
Create a student model from the data retrieved from the repository
Note: Something looks strange when reading from the repository. If the items in the repository are StudentPersonalDetails why create new instances
We can stub retrieving the student data like so
public class StudentServiceShould
{
[Theory]
[InlineData(1)]
public void AbleToRetrieveStudentById(int n)
{
var students = new []{
// new Domain.Entities.StudentPersonalDetails for student role 1,
// new Domain.Entities.StudentPersonalDetails for student role 2,
// new Domain.Entities.StudentPersonalDetails for student role 3
};
var mock = new Mock<IStudentPersonalDetailsRepository>();
mock.SetupGet(mk => mk.StudentPersonalDetails).Returns(students.AsQueryable());
var logger = new Mock<ILogger<StudentsPersonalDetailsService>> ();
var ob = new StudentsPersonalDetailsService(mock.Object, logger.Object);
}
}
Creating the StudentModel objects is encapsulated in the Translator but because it is a static method on the 'StudentModel' we cannot mock it and will have to test the reading and conversion in one go.

how to map sitecore items using glassmapper class in web froms..?

i'm creating demo project there i create Item which contains sub-Item now i want to render these using web controller my code like this
site items created as following image
and my glass mapper code is as:
public static class GlassMapperSc
{
public static void Start()
{
//create the resolver
var resolver = DependencyResolver.CreateStandardResolver();
//install the custom services
GlassMapperScCustom.CastleConfig(resolver.Container);
//create a context
var context = Glass.Mapper.Context.Create(resolver);
context.Load(
GlassMapperScCustom.GlassLoaders()
);
GlassMapperScCustom.PostLoad();
}
public class DesktopHome
{
public virtual string Title { get; set; }
public virtual string Description { get; set; }
public virtual string LeftRotatorTitle { get; set; }
public virtual string RightRotatorTitle { get; set; }
}
public class GlobalsItem
{
public class HeaderTemplateItem
{
public class NavItem
{
public virtual string Title { get; set; }
public virtual string Link { get; set; }
public virtual IEnumerable<NavItem> Children { get; set; }
}
}
}
}
i'm able to get parent items but not able to get child items please anyone help me to figure out this issue
Define your Modal Class as:
[SitecoreClass]
public class Header
{
[SitecoreInfo(SitecoreInfoType.Url)]
public virtual string About{ get; set; }
[SitecoreField]
public virtual string Home{ get; set; }
[SitecoreField]
public virtual string Services{ get; set; }
[SitecoreField]
public virtual IEnumerable<Header> Links { get; set; }
}
Configuring the application
To configure Glass Mapper is really straight forward. Open or create a Global.ascx file in your project and on the application start add the following code:
protected void Application_Start(object sender, EventArgs e)
{
AttributeConfigurationLoader loader = new AttributeConfigurationLoader(
new string[] { "Glass.Sitecore.Mapper.Demo.Application.Domain, Glass.Sitecore.Mapper .Demo" }
);
Persistence.Context context = new Context(loader, null);
}
your view code will be as:
<div>
<h1>
<asp:Literal runat="server" ID="About" />
</h1>
<div class="body">
<asp:Literal runat="server" ID="Home" />
</div>
<div class="links">
<asp:Repeater runat="server" ID="links">
<HeaderTemplate>
<ul>
</HeaderTemplate>
<ItemTemplate>
<li><a href='<%# DataBinder.Eval(Container.DataItem,"Url") %>'>
<%# DataBinder.Eval(Container.DataItem,"Services") %></a> </li>
</ItemTemplate>
<FooterTemplate>
</ul>
</FooterTemplate>
</asp:Repeater>
</div>
Next lets look at the code behind page, for simplicity everything is going in the Page_Load method:
protected void Page_Load(object sender, EventArgs e)
{
ISitecoreContext context = new SitecoreContext();
DemoClass item = context.GetCurrentItem<DemoClass>();
title.Text = item.Title;
body.Text = item.Body;
links.DataSource = item.Links;
links.DataBind();
}

Caused by: org.hibernate.PropertyValueException: not-null property references a null or transient value:

Hi here is Bussinss object class where pwdId and userId are notnull in db
#Entity
#Table(name="CLOUD_SVR_PASSWORDS_HISTORY")
#NamedQuery(name="CloudSvrPasswordsHistory.findAll", query="SELECT c FROM CloudSvrPasswordsHistory c")
public class CloudSvrPasswordsHistory implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue
#Column(name="PWD_ID",nullable=false)
private long pwdId;
#Column(name="OLD_PASSWORD")
private String oldPassword;
#Column(name="CURRENT_PASSWORD")
private String currentPassword;
#Column(name="PWD_CHANGE_TYPE")
private String pwdChangeType;
#Column(name="CREATED_DATE")
private Timestamp createdDate;
#ManyToOne
#JoinColumn(name="USER_ID",nullable=false)
private CloudSvrUser user;
public long getPwdId() {
return pwdId;
}
public void setPwdId(long pwdId) {
this.pwdId = pwdId;
}
public String getOldPassword() {
return oldPassword;
}
public void setOldPassword(String oldPassword) {
this.oldPassword = oldPassword;
}
public String getCurrentPassword() {
return currentPassword;
}
public void setCurrentPassword(String currentPassword) {
this.currentPassword = currentPassword;
}
public String getPwdChangeType() {
return pwdChangeType;
}
public void setPwdChangeType(String pwdChangeType) {
this.pwdChangeType = pwdChangeType;
}
public Timestamp getCreatedDate() {
return createdDate;
}
public void setCreatedDate(Timestamp createdDate) {
this.createdDate = createdDate;
}
public CloudSvrUser getUser() {
return user;
}
public void setUser(CloudSvrUser user) {
this.user = user;
}
here is my service implementation class only one method I am specifyng
#Transactional
public void changePassword(CloudSvrPasswordsHistory pwdInfo)throws BusinessException
{
//String password=null;
try{
System.out.println("servcimpl----------");
CloudSvrUser dbUser =getUser(pwdInfo);
if(dbUser != null){
List<CloudSvrPasswordsHistory> newPwdList = new ArrayList<CloudSvrPasswordsHistory>();
CloudSvrPasswordsHistory changedPwd = new CloudSvrPasswordsHistory();
changedPwd.setOldPassword(pwdInfo.getOldPassword());
changedPwd.setCurrentPassword(pwdInfo.getCurrentPassword());
newPwdList.add(changedPwd);
dbUser.setPassCode(changedPwd.getCurrentPassword());
//set childs to parent
pwdInfo.setUser(dbUser);
dbUser.setUserPwdList(newPwdList);
//password=
changedPwd(dbUser);
System.out.println("serviceimplend---------");
}
}
catch(DaoException daoexception)
{
throw new BusinessException(daoexception.getMessage());
}
//return password;
}
here is my DAOImpl class
#Repository("passwordDao")
public class PasswordDaoImpl extends BaseDaoImpl implements PasswordDao
{
PasswordDaoImpl()
{}
public void ChangedPwd(CloudSvrUser user)
{
//String password=null;
List<CloudSvrPasswordsHistory> pwdinfo = user.getUserPwdList();
for(CloudSvrPasswordsHistory changedPwd:pwdinfo)
{
//changedPwd.setPwdId((new Long(1)));
changedPwd.setCreatedDate(new Timestamp(System.currentTimeMillis()));
changedPwd.setPwdChangeType("ByUser");
}
try{
super.getHibernateTemplate().update(user);
//this.userDao.updateUser(dbUser);
}
catch(DataAccessException accessException){
throw new DaoException("Internal DB error occured.");
}
//return password ;
}
when giving request getting exception in console
Caused by: org.hibernate.PropertyValueException: not-null property references a null or transient value: com.omnypay.dao.bo.CloudSvrPasswordsHistory.user
please help me
The error says the user property of CloudSvrPasswordsHistory entity is null, where as hibernate is expecting it to be not-null, this is because you told hibernate that nullable=false for user property using this mapping:
#ManyToOne
#JoinColumn(name="USER_ID",nullable=false)
private CloudSvrUser user;
So to fix the issue you have to set the user property for your CloudSvrPasswordsHistory entity as:
changedPwd.setUser(dbUser);

Silverlight: Parent ViewModel Property value to Child ViewModel property

I posted this question on the Silverlight forums, but haven't been able to get an answer to solve my issue, so I hope the guru's at SO can help!
Basically I have an entity property in my parent viewmodel. When this entity changes I need the ID of the entity in my child viewmodel. I have created a child control with a dependency property and created a binding in the constructor. I am trying to implement all this using MVVM and MEF.
My ParentViewModel:
[ExportPlugin(ViewModelTypes.ParentViewModel, PluginType.ViewModel)]
[PartCreationPolicy(CreationPolicy.NonShared)]
public class ParentViewModel: ViewModelBase
{
private Person _currentPerson;
public Person CurrentPerson
{
get { return _currentPerson; }
private set
{
if (!ReferenceEquals(_currentPerson, value))
{
_currentPerson= value;
RaisePropertyChanged("CurrentPerson");
}
}
}
}
My ParentUserControl:
<UserControl x:Class="MyApp.ParentUserControl" x:Name="ParentControl">
<local:ChildUserControl PersonID="{Binding ElementName=ParentControl, Mode=TwoWay, Path=DataContext.CurrentPerson.ID}" />
</UserControl>
My ChildUserControl codebehind:
public partial class ChildUserControl : UserControl
{
#region Private Properties
private PluginCatalogService _catalogService = PluginCatalogService.Instance;
#endregion
#region Dependency Properties
public static readonly DependencyProperty PersonIDProperty =
DependencyProperty.Register("PersonID", typeof(int), typeof(ChildUserControl), new PropertyMetadata(OnPersonIDChanged));
#endregion
#region Public Properties
public int PersonID
{
get { return (int)GetValue(PersonIDProperty); }
set { SetValue(PersonIDProperty, value); }
}
#endregion
#region Constructor
public ChildUserControl()
{
InitializeComponent();
if (!ViewModelBase.IsInDesignModeStatic)
this.DataContext = _catalogService.FindPlugin(ViewModelTypes.ChildViewModel, PluginType.ViewModel);
this.SetBinding(PersonIDProperty, new Binding("PersonID") { Mode = BindingMode.TwoWay, Source = DataContext, UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged });
}
#endregion
private static void OnPersonIDChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
...
}
My ChildViewModel:
[ExportPlugin(ViewModelTypes.ChildViewModel, PluginType.ViewModel)]
[PartCreationPolicy(CreationPolicy.NonShared)]
public class ChildViewModel: ViewModelBase
{
private int _personID;
public int PersonID
{
get { return _personID; }
set
{
if (!ReferenceEquals(_personID, value))
{
_personID= value;
RaisePropertyChanged("PersonID");
}
}
}
}
I created the OnPersonIDChanged event to see if when the CurrentPerson entity changed, the change was being picked up in the ChildControl, which it is. It just isn't being picked up in the ChildControl ViewModel.
Any help is much appreciated.
Preferably, if you are using PRISM you can use the EventAggregator...
see http://msdn.microsoft.com/en-us/library/ff921122(v=pandp.40).aspx and https://compositewpf.codeplex.com/
Another option would be to hook (hack) onto the PropertyChanged
ViewModel1.PropertyChanged += (s, e) =>
{
if (e.PropertyName == "XXX")
{
ViewModel2.PropertyX = vm1.PropertY;
}
};