Search Results

Search found 1086 results on 44 pages for 'persist'.

Page 12/44 | < Previous Page | 8 9 10 11 12 13 14 15 16 17 18 19  | Next Page >

  • Setup database for Unit tests with Spring, Hibernate and Spring Transaction Support

    - by Michael Bulla
    I want to test integration of dao-layer with my service-layer in a unit-test. So I need to setup some data in my database (hsql). For this setup I need an own transaction at the begining of my testcase to ensure that all my setup is really commited to database before starting my testcase. So here's what I want to achieve: // NotTranactional public void doTest { // transaction begins setup database // commit transaction service.doStuff() // doStuff is annotated @Transactional(propagation=Propagation.REQUIRED) } Here is my not working code: @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations={"/asynchUnit.xml"}) @DirtiesContext(classMode=ClassMode.AFTER_EACH_TEST_METHOD) public class ReceiptServiceTest implements ApplicationContextAware { @Autowired(required=true) private UserHome userHome; private ApplicationContext context; @Before @Transactional(propagation=Propagation.REQUIRED) public void init() throws Exception { User user = InitialCreator.createUser(); userHome.persist(user); } @Test public void testDoSomething() { ... } } Leading to this exception: org.hibernate.HibernateException: No Hibernate Session bound to thread, and configuration does not allow creation of non-transactional one here at org.springframework.orm.hibernate3.SpringSessionContext.currentSession(SpringSessionContext.java:63) at org.hibernate.impl.SessionFactoryImpl.getCurrentSession(SessionFactoryImpl.java:687) at de.diandan.asynch.modell.GenericHome.getSession(GenericHome.java:40) at de.diandan.asynch.modell.GenericHome.persist(GenericHome.java:53) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:318) at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:196) at $Proxy28.persist(Unknown Source) at de.diandan.asynch.service.ReceiptServiceTest.init(ReceiptServiceTest.java:63) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:44) at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15) at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:41) at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:27) at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:74) at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:83) at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:72) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:231) at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50) at org.junit.runners.ParentRunner$3.run(ParentRunner.java:193) at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:52) at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:191) at org.junit.runners.ParentRunner.access$000(ParentRunner.java:42) at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:184) at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61) at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:71) at org.junit.runners.ParentRunner.run(ParentRunner.java:236) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:174) at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:49) at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197) I dont know whats the right way to get the transaction around setup database. What I tried: @Before @Transactional(propagation=Propagation.REQUIRED) public void setup() { setup database } - Spring seems not to start transaction in @Before-annotated methods. Beyond that, thats not what I really want, cause there are a lot merhods in my testclass which needs a slightly differnt setup, so I need several of that init-methods. @Transactional(propagation=Propagation.REQUIRED) public void setup() { setup database } public void doTest { init(); service.doStuff() // doStuff is annotated @Transactional(propagation=Propagation.REQUIRED) } -- init seems not to get started in transaction What I dont want to do: public void doTest { // doing my own transaction-handling setup database // doing my own transaction-handling service.doStuff() // doStuff is annotated @Transactional(propagation=Propagation.REQUIRED) } -- start mixing springs transaction-handling and my own seems to get pain in the ass. @Transactional(propagation=Propagation.REQUIRED) public void doTest { setup database service.doStuff() } -- I want to test as real as possible situation, so my service should start with a clean session and no transaction opened So whats the right way to setup database for my testcase?

    Read the article

  • Changing the action of a hyperlink in a Silverlight RichTextArea

    - by Marc Schluper
    The title of this post could also have been "Move over Hyperlink, here comes Actionlink" or "Creating interactive text in Silverlight." But alas, there can be only one. Hyperlinks are very useful. However, they are also limited because their action is fixed: browse to a URL. This may have been adequate at the start of the Internet, but nowadays, in web applications, the one thing we do not want to happen is a complete change of context. In applications we typically like a hyperlink selection to initiate an action that updates a part of the screen. For instance, if my application has a map displayed with some text next to it, the map would react to a selection of a hyperlink in the text, e.g. by zooming in on a location and displaying additional locational information in a popup. In this way, the text becomes interactive text. It is quite common that one company creates and maintains websites for many client companies. To keep maintenance cost low, it is important that the content of these websites can be updated by the client companies themselves, without the need to involve a software engineer. To accommodate this scenario, we want the author of the interactive text to configure all hyperlinks (without writing any code). In a Silverlight RichTextArea, the default action of a Hyperlink is the same as a traditional hyperlink, but it can be changed: if the Command property has a value then upon a click event this command is called with the value of the CommandParameter as parameter. How can we let the author of the text specify a command for each hyperlink in the text, and how can we let an application react properly to a hyperlink selection event? We are talking about any command here. Obviously, the application would recognize only a specific set of commands, with well defined parameters, but the approach we take here is generic in the sense that it pertains to the RichTextArea and any command. So what do we require? We wish that: As a text author, I can configure the action of a hyperlink in a (rich) text without writing code; As a text author, I can persist the action of a hyperlink with the text; As a reader of persisted text, I can click a hyperlink and the configured action will happen; As an application developer, I can configure a control to use my application specific commands. In an excellent introduction to the RichTextArea, John Papa shows (among other things) how to persist a text created using this control. To meet our requirements, we can create a subclass of RichTextArea that uses John's code and allows plugging in two command specific components: one to prompt for a command definition, and one to execute the command. Since both of these plugins are application specific, our RichTextArea subclass should not assume anything about them except their interface. public interface IDefineCommand { void Prompt(string content, // the link content Action<string, object> callback); // the method called to convey the link definition } public interface IPerformCommand : ICommand {} The IDefineCommand plugin receives the content of the link (the text visible to the reader) and displays some kind of control that allows the author to define the link. When that's done, this (possibly changed) content string is conveyed back to the RichTextArea, together with an object that defines the command to execute when the link is clicked by the reader of the published text. The IPerformCommand plugin simply implements System.Windows.Input.ICommand. Let's use MEF to load the proper plugins. In the example solution there is a project that contains rudimentary implementations of these. The IDefineCommand plugin simply prompts for a command string (cf. a command line or query string), and the IPerformCommand plugin displays a MessageBox showing this command string. An actual application using this extended RichTextArea would have its own set of commands, each having their own parameters, and hence would provide more user friendly application specific plugins. Nonetheless, in any case a command can be persisted as a string and hence the two interfaces defined above suffice. For a Visual Studio 2010 solution, see my article on The Code Project.

    Read the article

  • [EF + ORACLE] Updating and Deleting Entities

    - by JTorrecilla
    Prologue In previous chapters we have seen how to insert data through EF, with and without sequences. In this one, we are going to see how to Update and delete Data from the DB. Updating data The update of the Entity Data (properties) is a very common and easy action. Before of change any of the properties of the Entity, we can check the EntityState property, and we can see that is EntityState.Unchanged.   For making an update it is needed to get the Entity which will be modified. In the following example, I use the GetEmployeeByNumber to get a valid Entity: 1: EMPLEADOS emp=GetEmployeeByNumber(2); 2: emp.Name="a"; 3: emp.Phone="2"; 4: emp.Mail="aa"; After modifying the desired properties of the Entity, we are going to check again Entitystate property, which now has the EntityState.Modified value. To persist the changes to the DB is necessary to invoke the SaveChanges function of our context. 1: context.SaveChanges(); After modifying the desired properties of the Entity, we are going to check again Entitystate property, which now has the EntityState.Modified value. To persist the changes to the DB is necessary to invoke the SaveChanges function of our context. If we check again the EntityState property we will see that the value will be EntityState.Unchanged.   Deleting Data Another easy action is to delete an Entity.   The first step to delete an Entity from the DB is to select the entity: 1: CLIENTS selectedClient = GetClientByNumber(15); 2: context.CLIENTES.DeleteObject(clienteSeleccionado); Before invoking the DeleteObject function, we will check EntityStet which value must be EntityState.Unchanged. After deleting the object, the state will be changed to EntitySate.Deleted. To commit the action we have to invoke the SaveChanges function. Aftar that, the EntityState property will be EntityState.Detached. Cascade Entity Framework lets cascade updates and deletes, although I never see cascade updates. What is a cascade delete? A cascade delete is an action that allows to delete all the related object to the object we desire to delete. This option could be established in the DB manager, or it could be in the EF model designer. For example: With a given relation (1-N) between clients and requests. The common situation must be to let delete those clients whose have no requests. If we select the relation between both entities, and press the second mouse button, we can see the properties panel of the relation. The props are: This grid shows the relations indicating the Master table(Clients) and the end point (Cabecera or Requests) The property “End 1 OnDelete” indicates the action to do when a Entity from the Master will be deleted. There are two options: - None: No action will be done, it is said, if a Entity has details entities it could not be deleted. - Cascade: It will delete all related entities to the master Entity. If we enable the cascade delete in a relation, and we invoke the DeleteObject function of the set, we could observe that all the related object indicates a Entitystate.Deleted state. Like an update, insert or common delete, until we commit the changes with SaveChanges function, the data would not be commited. Si habilitamos el borrado en cascada de una relación, e invocamos a la función DeleteObject del conjunto, podremos observar que todas las entidades de Detalle (de la relación indicada) presentan el valor EntityState.Deleted en la propiedad EntityState. Del mismo modo que en el borrado, inserción o actualización, hasta que no se invoque al método SaveChanges, los cambios no van a ser confirmados en la Base de Datos. Finally In this chapter we have seen how to update a Entity, how to delete an Entity and how to implement Cascade Deleting through EF. In next chapters we will see how to query the DB data.

    Read the article

  • How to handle EntityExistsException properly?

    - by Ivan Yatskevich
    I have two entities: Question and FavoritesCounter. FavoritesCounter should be created when the question is added to favorites for the first time. Consider a use case when two users tries to add a question to favorites simultaneously - this will cause EntityExistsException when entityManager.persist(counter) is called for the second user. But the code below doesn't work, because when EntityExistsException is thrown, container marks transaction as rollback only and attempt to return getFavoritesCounter(question) fails with javax.resource.ResourceException: Transaction is not active @Stateless public class FavoritesServiceBean implements FavoritesService { ... public void addToFavorites(Question question) { FavoritesCounter counter = getCounter(question); if (counter == null) { counter = createCounter(question); } //increase counter } private FavoritesCounter createCounter(Question question) { try { FavoritesCounter counter = new FavoritesCounter(); counter.setQuestion(question); entityManager.persist(counter); entityManager.flush(); return counter; } catch (EntityExistsException e) { return getFavoritesCounter(question); } } private FavoritesCounter getFavoritesCounter(Question question) { Query counterQuery = entityManager.createQery("SELECT counter FROM FavoritesCounter counter WHERE counter.question = :question"); counterQuery.setParameter("question", question); List<FavoritesCounter> result = counterQuery.getResultList(); if (result.isEmpty()) return null; return result.get(0); } } Question @Entity public class Question implements Serializable { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; //getter and setter for id } FavoritesCounter @Entity public class FavoritesCounter implements Serializable { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; @OneToOne @Column(unique = true) private Question question; //getter and setter } What is the best way to handle such a situation - return already created entity after EntityExistsException?

    Read the article

  • Google App Engine: JDO does the job, JPA does not

    - by Phuong Nguyen de ManCity fan
    I have setup a project using both Jdo and Jpa. I used Jpa Annotation to Declare my Entity. Then I setup my testCases based on LocalTestHelper (from Google App Engine Documentation). When I run the test, a call to makePersistent of Jdo:PersistenceManager is perfectly OK; a call to persist of Jpa:EntityManager raised an error: java.lang.IllegalArgumentException: Type ("org.seamoo.persistence.jpa.model.ExampleModel") is not that of an entity but needs to be for this operation at org.datanucleus.jpa.EntityManagerImpl.assertEntity(EntityManagerImpl.java:888) at org.datanucleus.jpa.EntityManagerImpl.persist(EntityManagerImpl.java:385) Caused by: org.datanucleus.exceptions.NoPersistenceInformationException: The class "org.seamoo.persistence.jpa.model.ExampleModel" is required to be persistable yet no Meta-Data/Annotations can be found for this class. Please check that the Meta-Data/annotations is defined in a valid file location. at org.datanucleus.ObjectManagerImpl.assertClassPersistable(ObjectManagerImpl.java:3894) at org.datanucleus.jpa.EntityManagerImpl.assertEntity(EntityManagerImpl.java:884) ... 27 more How can it be the case? Below is the link to the source code of the maven projects that reproduce that problem: http://seamoo.com/jpa-bug-reproduce.tar.gz Execute the maven test goal over the parent pom you will notice that 3/4 tests from org.seamoo.persistence.jdo.JdoGenericDAOImplTest passed, while all tests from org.seamoo.persistence.jpa.JpaGenericDAOImplTest failed.

    Read the article

  • Problem retrieving multiple instances of the same asp.net session variable

    - by sw1sh
    I'm having problems with retrieving multiple instances of a session variable from an InProc session state. In the following code I persist a simple BusinessObject into a session variable on the Page_Load event. On the click of a button I try to retrieve the object back into 2 new declared instances of the same BusinessObject. All works great until I change one of the properties in the first instance, it changes the second instance as well. Is this normal behaviour? I would have thought as these were new instances they wouldn’t demonstrate static behaviour? Any ideas where I'm going wrong? Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load If Not Page.IsPostBack Then ' create a new instance of a business object and set a containg variable Dim BO As New BusinessObject BO.SomeVariable = "test" ' persist to inproc session Session("BO") = BO End If End Sub Protected Sub btnRetrieveSessionVariable_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnRetrieveSessionVariable.Click ' retrieve the session variable to a new instance of BusinessObject Dim BO1 As New BusinessObject If Not Session("BO") Is Nothing Then BO1 = Session("BO") ' retrieve the session variable to a new instance of BusinessObject Dim BO2 As New BusinessObject If Not Session("BO") Is Nothing Then BO2 = Session("BO") ' change the property value on the first instance BO1.SomeVariable = "test2" ' why has this changed on both instances? Dim strBO1Property As String = BO1.SomeVariable Dim strBO2Property As String = BO2.SomeVariable End Sub ' simple BusinessObject class Public Class BusinessObject Private _SomeVariable As String Public Property SomeVariable() As String Get Return _SomeVariable End Get Set(ByVal value As String) _SomeVariable = value End Set End Property End Class

    Read the article

  • How to force ADO.Net to use only the System.String DataType in the readers TableSchema.

    - by Keith Sirmons
    Howdy, I am using an OleDbConnection to query an Excel 2007 Spreadsheet. I want force the OleDbDataReader to use only string as the column datatype. The system is looking at the first 8 rows of data and inferring the data type to be Double. The problem is that on row 9 I have a string in that column and the OleDbDataReader is returning a Null value since it could not be cast to a Double. I have used these connection strings: Provider=Microsoft.ACE.OLEDB.12.0;Data Source="ExcelFile.xlsx";Persist Security Info=False;Extended Properties="Excel 12.0;IMEX=1;HDR=No" Provider=Microsoft.Jet.OLEDB.4.0;Data Source="ExcelFile.xlsx";Persist Security Info=False;Extended Properties="Excel 8.0;HDR=No;IMEX=1" Looking at the reader.GetSchemaTable().Rows[7].ItemArray[5], it's dataType is Double. Row 7 in this schema correlates with the specific column in Excel I am having issues with. ItemArray[5] is its DataType column Is it possible to create a custom TableSchema for the reader so when accessing the ExcelFiles, I can treat all cells as text instead of letting the system attempt to infer the datatype? I found some good info at this page: Tips for reading Excel spreadsheets using ADO.NET The main quirk about the ADO.NET interface is how datatypes are handled. (You'll notice I've been carefully avoiding the question of which datatypes are returned when reading the spreadsheet.) Are you ready for this? ADO.NET scans the first 8 rows of data, and based on that guesses the datatype for each column. Then it attempts to coerce all data from that column to that datatype, returning NULL whenever the coercion fails! Thank you, Keith Here is a reduced version of my code: using (OleDbConnection connection = new OleDbConnection(BuildConnectionString(dataMapper).ToString())) { connection.Open(); using (OleDbCommand cmd = new OleDbCommand()) { cmd.Connection = connection; cmd.CommandText = SELECT * from [Sheet1$]; using (OleDbDataReader reader = cmd.ExecuteReader()) { using (DataTable dataTable = new DataTable("TestTable")) { dataTable.Load(reader); base.SourceDataSet.Tables.Add(dataTable); } } } }

    Read the article

  • The type of field isn't supported by declared persistence strategy "OneToMany"

    - by Robert
    We are new to JPA and trying to setup a very simple one to many relationship where a pojo called Message can have a list of integer group id's defined by a join table called GROUP_ASSOC. Here is the DDL: CREATE TABLE "APP"."MESSAGE" ( "MESSAGE_ID" INTEGER NOT NULL GENERATED ALWAYS AS IDENTITY (START WITH 1, INCREMENT BY 1) ); ALTER TABLE "APP"."MESSAGE" ADD CONSTRAINT "MESSAGE_PK" PRIMARY KEY ("MESSAGE_ID"); CREATE TABLE "APP"."GROUP_ASSOC" ( "GROUP_ID" INTEGER NOT NULL, "MESSAGE_ID" INTEGER NOT NULL ); ALTER TABLE "APP"."GROUP_ASSOC" ADD CONSTRAINT "GROUP_ASSOC_PK" PRIMARY KEY ("MESSAGE_ID", "GROUP_ID"); ALTER TABLE "APP"."GROUP_ASSOC" ADD CONSTRAINT "GROUP_ASSOC_FK" FOREIGN KEY ("MESSAGE_ID") REFERENCES "APP"."MESSAGE" ("MESSAGE_ID"); Here is the pojo: @Entity @Table(name = "MESSAGE") public class Message { @Id @Column(name = "MESSAGE_ID") @GeneratedValue(strategy = GenerationType.IDENTITY) private int messageId; @OneToMany(fetch=FetchType.LAZY, cascade=CascadeType.PERSIST) private List groupIds; public int getMessageId() { return messageId; } public void setMessageId(int messageId) { this.messageId = messageId; } public List getGroupIds() { return groupIds; } public void setGroupIds(List groupIds) { this.groupIds = groupIds; } } When we try to execute the following test code we get <openjpa-1.2.3-SNAPSHOT-r422266:907835 fatal user error> org.apache.openjpa.util.MetaDataException: The type of field "pojo.Message.groupIds" isn't supported by declared persistence strategy "OneToMany". Please choose a different strategy. Message msg = new Message(); List groups = new ArrayList(); groups.add(101); groups.add(102); EntityManager em = Persistence.createEntityManagerFactory("TestDBWeb").createEntityManager(); em.getTransaction().begin(); em.persist(msg); em.getTransaction().commit(); Help!

    Read the article

  • CIL and JVM Little endian to big endian in c# and java

    - by Haythem
    Hello, I am using on the client C# where I am converting double values to byte array. I am using java on the server and I am using writeDouble and readDouble to convert double values to byte arrays. The problem is the double values from java at the end are not the double values at the begin giving to c# writeDouble in Java Converts the double argument to a long using the doubleToLongBits method , and then writes that long value to the underlying output stream as an 8-byte quantity, high byte first. DoubleToLongBits Returns a representation of the specified floating-point value according to the IEEE 754 floating-point "double format" bit layout. The Program on the server is waiting of 64-102-112-0-0-0-0-0 from C# to convert it to 1700.0 but he si becoming 0000014415464 from c# after c# converted 1700.0 this is my code in c#: class User { double workingStatus; public void persist() { byte[] dataByte; using (MemoryStream ms = new MemoryStream()) { using (BinaryWriter bw = new BinaryWriter(ms)) { bw.Write(workingStatus); bw.Flush(); bw.Close(); } dataByte = ms.ToArray(); for (int j = 0; j < dataByte.Length; j++) { Console.Write(dataByte[j]); } } public double WorkingStatus { get { return workingStatus; } set { workingStatus = value; } } } class Test { static void Main() { User user = new User(); user.WorkingStatus = 1700.0; user.persist(); } thank you for the help.

    Read the article

  • Hibernate mapping - "Could not determine type"

    - by Pool
    I currently have the following objects persisting successfully: Person first name, etc. Exams title, date, etc. I'd like to now create a third table Exam results. For this table I believe it should be person ID, exam ID and result, and this is a many to many relationship. @Entity public class ExamResult { private Exam exam; private Person person; private double value; @Id @ManyToOne( cascade = {CascadeType.PERSIST, CascadeType.MERGE} ) @JoinColumn(name="EXAM_ID") public Exam getExam() { return exam; } public void setExam(Exam exam) { this.exam = exam; } @Id @ManyToOne( cascade = {CascadeType.PERSIST, CascadeType.MERGE} ) @JoinColumn(name="PERSON_ID") public Person getPerson() { return person; } public void setPerson(Person person) { this.person = person; } public double getValue() { return value; } public void setValue(double value) { this.value = value; } } The error: org.hibernate.MappingException: Could not determine type for: Person, at table: ExamResult, for columns: [org.hibernate.mapping.Column(person)] I think I may be going about this the wrong way, but I can't work out how to proceed with this relationship from the tutorial. Any ideas?

    Read the article

  • JPA @ManyToMany on only one side?

    - by Ethan Leroy
    I am trying to refresh the @ManyToMany relation but it gets cleared instead... My Project class looks like this: @Entity public class Project { ... @ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER) @JoinTable(name = "PROJECT_USER", joinColumns = @JoinColumn(name = "PROJECT_ID", referencedColumnName = "ID"), inverseJoinColumns = @JoinColumn(name = "USER_ID", referencedColumnName = "ID")) private Collection<User> users; ... } But I don't have - and I don't want - the collection of Projects in the User entity. When I look at the generated database tables, they look good. They contain all columns and constraints (primary/foreign keys). But when I persist a Project that has a list of Users (and the users are still in the database), the mapping table doesn't get updated gets updated but when I refresh the project afterwards, the list of Users is cleared. For better understanding: Project project = ...; // new project with users that are available in the db System.out.println(project getUsers().size()); // prints 5 em.persist(project); System.out.println(project getUsers().size()); // prints 5 em.refresh(project); System.out.println(project getUsers().size()); // prints 0 So, how can I refresh the relation between User and Project?

    Read the article

  • Netbean6.8: Cant deploy an webapp with Message Driven Bean

    - by Harry Pham
    I create an Enterprise Application CustomerApp that also generated two projects CustomerApp-ejb and CustomerApp-war. In the CustomerApp-ejb, I create a SessionBean call CustomerSessionBean.java as below. package com.customerapp.ejb; import javax.ejb.Stateless; import javax.ejb.LocalBean; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; @Stateless @LocalBean public class CustomerSessionBean { @PersistenceContext(unitName = "CustomerApp-ejbPU") private EntityManager em; public void persist(Object object) { em.persist(object); } } Now I can deploy CustomerApp-war just fine. But as soon as I create a Message Driven Bean, I cant deploy CustomerApp-war anymore. When I create NotificationBean.java (message driven bean), In the project destination option, I click add, and have NotificationQueue for the Destination Name and Destination Type is Queue. Below are the code package com.customerapp.mdb; import javax.ejb.ActivationConfigProperty; import javax.ejb.MessageDriven; import javax.jms.Message; import javax.jms.MessageListener; @MessageDriven(mappedName = "jms/NotificationQueue", activationConfig = { @ActivationConfigProperty(propertyName = "acknowledgeMode", propertyValue = "Auto-acknowledge"), @ActivationConfigProperty(propertyName = "destinationType", propertyValue = "javax.jms.Queue") }) public class NotificationBean implements MessageListener { public NotificationBean() { } public void onMessage(Message message) { } } If I remove the @MessageDriven annotation, then I can deploy the project. Any idea why and how to fix it?

    Read the article

  • SqlCe odd results why? -- Same SQL, different results in different apps. Issue with

    - by NitroxDM
    When I run this SQl in my mobile app I get zero rows. select * from inventory WHERE [ITEMNUM] LIKE 'PUMP%' AND [LOCATION] = 'GARAGE' When I run the same SQL in Query Analyzer 3.5 using the same database I get my expected one row. Why the difference? Here is the code I'm using in the mobile app: SqlCeCommand cmd = new SqlCeCommand(Query); cmd.Connection = new SqlCeConnection("Data Source="+filePath+";Persist Security Info=False;"); DataTable tmpTable = new DataTable(); cmd.Connection.Open(); SqlCeDataReader tmpRdr = cmd.ExecuteReader(); if (tmpRdr.Read()) tmpTable.Load(tmpRdr); tmpRdr.Close(); cmd.Connection.Close(); return tmpTable; UPDATE: For the sake of trying I used the code found in one of the answers found here and it works as expected. So my code looks like this: SqlCeConnection conn = new SqlCeConnection("Data Source=" + filePath + ";Persist Security Info=False;"); DataTable tmpTable = new DataTable(); SqlCeDataAdapter AD = new SqlCeDataAdapter(Query, conn); AD.Fill(tmpTable); The issue appears to be with the SqlCeDataReader. Hope this helps someone else out!

    Read the article

  • Netbean6.8: Cant deploy an app if I have Message Driven Bean

    - by Harry Pham
    I create an Enterprise Application CustomerApp that also generated two projects CustomerApp-ejb and CustomerApp-war. In the CustomerApp-ejb, I create a SessionBean call CustomerSessionBean.java as below. package com.customerapp.ejb; import javax.ejb.Stateless; import javax.ejb.LocalBean; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; @Stateless @LocalBean public class CustomerSessionBean { @PersistenceContext(unitName = "CustomerApp-ejbPU") private EntityManager em; public void persist(Object object) { em.persist(object); } } Now I can deploy CustomerApp-war just fine. But as soon as I create a Message Driven Bean, I cant deploy CustomerApp-war anymore. When I create NotificationBean.java (message driven bean), In the project destination option, I click add, and have NotificationQueue for the Destination Name and Destination Type is Queue. Below are the code package com.customerapp.mdb; import javax.ejb.ActivationConfigProperty; import javax.ejb.MessageDriven; import javax.jms.Message; import javax.jms.MessageListener; @MessageDriven(mappedName = "jms/NotificationQueue", activationConfig = { @ActivationConfigProperty(propertyName = "acknowledgeMode", propertyValue = "Auto-acknowledge"), @ActivationConfigProperty(propertyName = "destinationType", propertyValue = "javax.jms.Queue") }) public class NotificationBean implements MessageListener { public NotificationBean() { } public void onMessage(Message message) { } } If I remove the @MessageDriven annotation, then I can deploy the project. Any idea why and how to fix it?

    Read the article

  • self referencing object in JPA

    - by geoaxis
    Hello, I am trying to save a SystemUser entity in JPA. I also want to save certain things like who created the SystemUser and who last modified the system User as well. @ManyToOne(targetEntity = SystemUser.class) @JoinColumn private SystemUser userWhoCreated; @Temporal(TemporalType.TIMESTAMP) @DateTimeFormat(iso=ISO.DATE_TIME) private Date timeCreated; @ManyToOne(targetEntity = SystemUser.class) @JoinColumn private SystemUser userWhoLastModified; @Temporal(TemporalType.TIMESTAMP) @DateTimeFormat(iso=ISO.DATE_TIME) private Date timeLastModified; I also want to ensure that these values are not null when persisted. So If I use the NotNull JPA annotation, that is easily solved (along with reference to another entity) The problem description is simple, I cannot save rootuser without having rootuser in the system if I am to use a DataLoader class to persist JPA entity. Every other later user can be easily persisted with userWhoModified as the "systemuser" , but systemuser it's self cannot be added in this scheme. Is there a way so persist this first system user (I am thinking with SQL). This is a typical bootstrap (chicken or the egg) problem i suppose.

    Read the article

  • Why delete-orphan needs "cascade all" to run in JPA/Hibernate ?

    - by Jerome C.
    Hello, I try to map a one-to-many relation with cascade "remove" (jpa) and "delete-orphan", because I don't want children to be saved or persist when the parent is saved or persist (security reasons due to client to server (GWT, Gilead)) But this configuration doesn't work. When I try with cascade "all", it runs. Why the delete-orphan option needs a cascade "all" to run ? here is the code (without id or other fields for simplicity, the class Thread defines a simple many-to-one property without cascade): when using the removeThread function in a transactional function, it does not run but if I edit cascade.Remove into cascade.All, it runs. @Entity public class Forum { private List<ForumThread> threads; /** * @return the topics */ @OneToMany(mappedBy = "parent", cascade = CascadeType.REMOVE, fetch = FetchType.LAZY) @Cascade(org.hibernate.annotations.CascadeType.DELETE_ORPHAN) public List<ForumThread> getThreads() { return threads; } /** * @param topics the topics to set */ public void setThreads(List<ForumThread> threads) { this.threads = threads; } public void addThread(ForumThread thread) { getThreads().add(thread); thread.setParent(this); } public void removeThread(ForumThread thread) { getThreads().remove(thread); } } thanks.

    Read the article

  • Path to XML DTD for DBUnit in multi-module Java/Maven project?

    - by HDave
    I have a multi-module maven project. Within the persist module I have a number of XML files data files that reference a DTD: <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE myapp-data SYSTEM "myapp-data.dtd" > <dataset> .....omitted for brevity.... </dataset> The DTD is stored in the same directory with the XML files and even Eclipse reports these XML files as valid. However, when I run the application, the DBUnit FlatXMLDataSet throws a FileNotFound exception because it cannot located the DTD. It is apparently looking for the DTD in the root project directory (e.g. myproject/). I would have expected it to look for the DTD in the same directory as the XML file itself (e.g. myproject/persist/target/test-data). Looking at the DBUnit source code, it has this to say about it "Relative DOCTYPE uri are resolved from the current working dicrectory." What's a good way to fix this?

    Read the article

  • EC2 persistence of machine

    - by Seagull
    I want to 'persist' my Amazon EC2 images. My scenario: I have a range of Windows and Linux machines Some machines are EBS backed, whereas others are S3 backed. I need to be able to persist a machine (put it to sleep), preferably keeping all settings active I had them when the machine was running. I need to be able to quickly wake up a machine from sleep [Ideally with an SLA of less than 2 min to turn-on, if such an SLA is available with Amazon]. Here's the stuff that confuses me: AWS allows me to put EBS backed machines to sleep, but not S3 backed. I believe I can put S3 machines into some sort of persistence mode. But this involves shutting down the machine, writing it to S3 storage and then recovering from there (not a real sleep mode, but at least I don't continue to get billed for CPU). S3 backing seems to take a long time to either writing a machine to disk, or to recover (turn on a machine). I can't tell immediately which machines are EBS backed and which are S3 backed? It seems like I can instantiate either type, but it's not immediately clear how Amazon decided whether a given machine should be EBS or S3 backed. Advice?

    Read the article

  • Zend_Auth and database session SaveHandler

    - by takeshin
    I have created Zend_Auth adapter implementing Zend_Auth_Adapter_Interface (similar to Pádraic's adapter) and created simple ACL plugin. Everything works fine with default session handler. So far, so good. As a next step I have created custom Session SaveHandler to persist session data in the database. My implementation is very similar to this one from parables-demo. Seems that everything is working fine. Session data are properly saved to the database, session objects are serialized, but authentication does not work when I enable this custom SaveHandler. I have debugged the authentication and all works fine up till the next request, when the authentication data are lost. I suspected, that is has something to do with the fact, that I use $adapter->write($object) instead $adapter->write($string), but the same happens with strings. I'm bootstrapping Zend_Application_Resource_Session in the first Bootstrap method, as early as possible. Does Zend_Auth need any extra configuration to persist data in the database? Why the authentity is being lost?

    Read the article

  • @PrePersist with entity inheritance

    - by gerry
    I'm having some problems with inheritance and the @PrePersist annotation. My source code looks like the following: _the 'base' class with the annotated updateDates() method: @javax.persistence.Entity @Inheritance(strategy = InheritanceType.TABLE_PER_CLASS) public class Base implements Serializable{ ... @Id @GeneratedValue protected Long id; ... @Column(nullable=false) @Temporal(TemporalType.TIMESTAMP) private Date creationDate; @Column(nullable=false) @Temporal(TemporalType.TIMESTAMP) private Date lastModificationDate; ... public Date getCreationDate() { return creationDate; } public void setCreationDate(Date creationDate) { this.creationDate = creationDate; } public Date getLastModificationDate() { return lastModificationDate; } public void setLastModificationDate(Date lastModificationDate) { this.lastModificationDate = lastModificationDate; } ... @PrePersist protected void updateDates() { if (creationDate == null) { creationDate = new Date(); } lastModificationDate = new Date(); } } _ now the 'Child' class that should inherit all methods "and annotations" from the base class: @javax.persistence.Entity @NamedQueries({ @NamedQuery(name=Sensor.QUERY_FIND_ALL, query="SELECT s FROM Sensor s") }) public class Sensor extends Entity { ... // additional attributes @Column(nullable=false) protected String value; ... // additional getters, setters ... } If I store/persist instances of the Base class to the database, everything works fine. The dates are getting updated. But now, if I want to persist a child instance, the database throws the following exception: MySQLIntegrityConstraintViolationException: Column 'CREATIONDATE' cannot be null So, in my opinion, this is caused because in Child the method "@PrePersist protected void updateDates()" is not called/invoked before persisting the instances to the database. What is wrong with my code?

    Read the article

  • Android SDK: hello world does not run

    - by Alex
    I have installed Java x64, Eclipse Classic Judo x64 + ADT Pluggin. OS win 7 x64. I did installation everything according to the manual. Then created first application and launched it. Emulator was launched but hello world was not. I have not idea what doing wrong. Do anyone knows of such error and my problem as a whole? thx Console log: [2012-10-06 13:35:42 - test] ------------------------------ [2012-10-06 13:35:42 - test] Android Launch! [2012-10-06 13:35:42 - test] adb is running normally. [2012-10-06 13:35:42 - test] Performing com.example.test.MainActivity activity launch [2012-10-06 13:35:42 - test] Automatic Target Mode: launching new emulator with compatible AVD 'AVD_41' [2012-10-06 13:35:42 - test] Launching a new emulator with Virtual Device 'AVD_41' [2012-10-06 13:35:42 - Emulator] Failed to create Context 0x3005 [2012-10-06 13:35:42 - Emulator] emulator: WARNING: Could not initialize OpenglES emulation, using software renderer. [2012-10-06 13:35:42 - Emulator] WARNING: Data partition already in use. Changes will not persist! [2012-10-06 13:35:42 - Emulator] WARNING: SD Card image already in use: C:\Users\Zewisa\.android\avd\AVD_41.avd/sdcard.img [2012-10-06 13:35:42 - Emulator] WARNING: Cache partition already in use. Changes will not persist! [2012-10-06 13:35:42 - Emulator] could not get wglGetExtensionsStringARB [2012-10-06 13:35:42 - Emulator] could not get wglGetExtensionsStringARB [2012-10-06 13:35:42 - Emulator] could not get wglGetExtensionsStringARB [2012-10-06 13:35:42 - Emulator] could not get wglGetExtensionsStringARB [2012-10-06 13:35:42 - Emulator] could not get wglGetExtensionsStringARB [2012-10-06 13:35:42 - Emulator] could not get wglGetExtensionsStringARB [2012-10-06 13:35:42 - Emulator] could not get wglGetExtensionsStringARB [2012-10-06 13:35:42 - Emulator] could not get wglGetExtensionsStringARB [2012-10-06 13:35:42 - Emulator] emulator: warning: opening audio input failed [2012-10-06 13:35:42 - Emulator]

    Read the article

  • Zend_Auth and database SaveHandler

    - by takeshin
    I have created Zend_Auth adapter implementing Zend_Auth_Adapter_Interface (similar to Pádraic's adapter) and created simple ACL plugin. Everything works fine with default session handler. So far, so good. As a next step I have created custom Session SaveHandler to persist session data in the database. My implementation is very similar to this one from parables-demo. Seems that everything is working fine. Session data are properly saved to the database, session objects are serialized, but authentication does not work when I enable this custom SaveHandler. I have debugged the authentication and all works fine up till the next request, when the authentication data are lost. I suspected, that is has something to do with the fact, that I use $adapter->write($object) instead $adapter->write($string), but the same happens with strings. I'm bootstrapping Zend_Application_Resource_Session in the first Bootstrap method, as early as possible. Does Zend_Auth need any extra configuration to persist data in the database? Why the authentity is being lost?

    Read the article

  • Two entities with @ManyToOne should join the same table

    - by Ivan Yatskevich
    I have the following entities Student @Entity public class Student implements Serializable { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; //getter and setter for id } Teacher @Entity public class Teacher implements Serializable { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; //getter and setter for id } Task @Entity public class Task implements Serializable { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; @ManyToOne(optional = false) @JoinTable(name = "student_task", inverseJoinColumns = { @JoinColumn(name = "student_id") }) private Student author; @ManyToOne(optional = false) @JoinTable(name = "student_task", inverseJoinColumns = { @JoinColumn(name = "teacher_id") }) private Teacher curator; //getters and setters } Consider that author and curator are already stored in DB and both are in the attached state. I'm trying to persist my Task: Task task = new Task(); task.setAuthor(author); task.setCurator(curator); entityManager.persist(task); Hibernate executes the following SQL: insert into student_task (teacher_id, id) values (?, ?) which, of course, leads to null value in column "student_id" violates not-null constraint Can anyone explain this issue and possible ways to resolve it?

    Read the article

  • Hibernate does not allow an embedded object with an int field to be null?

    - by Jason Novak
    Hibernate does not allow me to persist an object that contains an null embedded object with an integer field. For example, if I have a class called Thing that looks like this @Entity public class Thing { @Id public String id; public Part part; } where Part is an embeddable class that looks like this @Embeddable public class Part { public String a; public int b; } then trying to persist a Thing object with a null Part causes Hibernate to throw an Exception. In particular, this code Thing th = new Thing(); th.id = "thing.1"; th.part = null; session.saveOrUpdate(th); causes Hibernate to throw this Exception org.hibernate.PropertyValueException: not-null property references a null or transient value: com.ace.moab.api.jobs.Thing.part My guess is that this is happening because Part is an embedded class and so Part.a and Part.b are simply columns in the Thing database table. Since the Thing.part is null Hibernate wants to set the Part.a and Part.b column values to null for the row for thing.1. However, Part.b is an integer and Hibernate will not allow integer columns in the database to be null. This is what causes the Exception, right? So I am looking for workarounds for this problem. I noticed making Part.b an Integer instead of an int seems to work, but for reasons I won't bore you with this is not a good option for us. Thanks!

    Read the article

  • Strange JPA one-to-many behavior when trying to set the "many" on the "one" entity

    - by errr
    I've mapped two entities using JPA (specifically Hibernate). Those entities have a one-to-many relationship (I've simplified for presentation): @Entity public class A { @ManyToOne public B getB() { return b; } } @Entity public Class B { @OneToMany(mappedBy="b") public Set<A> getAs() { return as; } } Now, I'm trying to create a relationship between two instances of these entities by using the setter of the one-side/not-owner-side of the relationship (i.e the table being referenced to): em.getTransaction().begin(); A a = new A(); B b = new B(); Set<A> as = new HashSet<A>(); as.add(a); b.setAs(as); em.persist(a); em.persist(b); em.getTransaction().commit(); But then, the relationship isn't persisted to the DB (the row created for entity A isn't referencing the row created for entity B). Why is it so? I'd excpect it to work. Also, if I remove the "mappedBy" property from the @OneToMany annotation it will work. Again - why is it so? and what are the possible effects for removing the "mappedBy" property?

    Read the article

< Previous Page | 8 9 10 11 12 13 14 15 16 17 18 19  | Next Page >