Search Results

Search found 636 results on 26 pages for 'serializable'.

Page 18/26 | < Previous Page | 14 15 16 17 18 19 20 21 22 23 24 25  | Next Page >

  • Jackson object mapping - map incoming JSON field to protected property in base class

    - by Pete
    We use Jersey/Jackson for our REST application. Incoming JSON strings get mapped to the @Entity objects in the backend by Jackson to be persisted. The problem arises from the base class that we use for all entities. It has a protected id property, which we want to exchange via REST as well so that when we send an object that has dependencies, hibernate will automatically fetch these dependencies by their ids. Howevery, Jackson does not access the setter, even if we override it in the subclass to be public. We also tried using @JsonSetter but to no avail. Probably Jackson just looks at the base class and sees ID is not accessible so it skips setting it... @MappedSuperclass public abstract class AbstractPersistable<PK extends Serializable> implements Persistable<PK> { @Id @GeneratedValue(strategy = GenerationType.AUTO) private PK id; public PK getId() { return id; } protected void setId(final PK id) { this.id = id; } Subclasses: public class A extends AbstractPersistable<Long> { private String name; } public class B extends AbstractPersistable<Long> { private A a; private int value; // getter, setter // make base class setter accessible @Override @JsonSetter("id") public void setId(Long id) { super.setId(id); } } Now if there are some As in our database and we want to create a new B via the REST resource: @POST @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) @Transactional public Response create(B b) { if (b.getA().getId() == null) cry(); } with a JSON String like this {"a":{"id":"1","name":"foo"},"value":"123"}. The incoming B will have the A reference but without an ID. Is there any way to tell Jackson to either ignore the base class setter or tell it to use the subclass setter instead? I've just found out about @JsonTypeInfo but I'm not sure this is what I need or how to use it. Thanks for any help!

    Read the article

  • Map enum in JPA with fixed values ?

    - by Kartoch
    I'm looking for the different ways to map an enum using JPA. I especially want to set the integer value of each enum entry and to save only the integer value. @Entity @Table(name = "AUTHORITY_") public class Authority implements Serializable { public enum Right { READ(100), WRITE(200), EDITOR (300); private int value; Right(int value) { this.value = value; } public int getValue() { return value; } }; @Id @GeneratedValue(strategy = GenerationType.AUTO) @Column(name = "AUTHORITY_ID") private Long id; // the enum to map : private Right right; } A simple solution is to use the Enumerated annotation with EnumType.ORDINAL: @Column(name = "RIGHT") @Enumerated(EnumType.ORDINAL) private Right right; But in this case JPA maps the enum index (0,1,2) and not the value I want (100,200,300). Th two solutions I found do not seem simple... First Solution A solution, proposed here, uses @PrePersist and @PostLoad to convert the enum to an other field and mark the enum field as transient: @Basic private int intValueForAnEnum; @PrePersist void populateDBFields() { intValueForAnEnum = right.getValue(); } @PostLoad void populateTransientFields() { right = Right.valueOf(intValueForAnEnum); } Second Solution The second solution proposed here proposed a generic conversion object, but still seems heavy and hibernate-oriented (@Type doesn't seem to exist in JEE): @Type( type = "org.appfuse.tutorial.commons.hibernate.GenericEnumUserType", parameters = { @Parameter( name = "enumClass", value = "Authority$Right"), @Parameter( name = "identifierMethod", value = "toInt"), @Parameter( name = "valueOfMethod", value = "fromInt") } ) Is there any other solutions ? I've several ideas in mind but I don't know if they exist in JPA: use the setter and getter methods of right member of Authority Class when loading and saving the Authority object an equivalent idea would be to tell JPA what are the methods of Right enum to convert enum to int and int to enum Because I'm using Spring, is there any way to tell JPA to use a specific converter (RightEditor) ?

    Read the article

  • JPA 2 Criteria API: why is isNull being ignored when in conjunction with equal?

    - by Vítor Souza
    I have the following entity class (ID inherited from PersistentObjectSupport class): @Entity public class AmbulanceDeactivation extends PersistentObjectSupport implements Serializable { private static final long serialVersionUID = 1L; @Temporal(TemporalType.DATE) @NotNull private Date beginDate; @Temporal(TemporalType.DATE) private Date endDate; @Size(max = 250) private String reason; @ManyToOne @NotNull private Ambulance ambulance; /* Get/set methods, etc. */ } If I do the following query using the Criteria API: CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery<AmbulanceDeactivation> cq = cb.createQuery(AmbulanceDeactivation.class); Root<AmbulanceDeactivation> root = cq.from(AmbulanceDeactivation.class); EntityType<AmbulanceDeactivation> model = root.getModel(); cq.where(cb.isNull(root.get(model.getSingularAttribute("endDate", Date.class)))); return em.createQuery(cq).getResultList(); I get the following SQL printed in the log: FINE: SELECT ID, REASON, ENDDATE, UUID, BEGINDATE, VERSION, AMBULANCE_ID FROM AMBULANCEDEACTIVATION WHERE (ENDDATE IS NULL) However, if I change the where() line in the previous code to this one: cq.where(cb.isNull(root.get(model.getSingularAttribute("endDate", Date.class))), cb.equal(root.get(model.getSingularAttribute("ambulance", Ambulance.class)), ambulance)); I get the following SQL: FINE: SELECT ID, REASON, ENDDATE, UUID, BEGINDATE, VERSION, AMBULANCE_ID FROM AMBULANCEDEACTIVATION WHERE (AMBULANCE_ID = ?) That is, the isNull criterion is totally ignored. It is as if it wasn't even there (if I provide only the equal criterion to the where() method I get the same SQL printed). Why is that? Is it a bug or am I missing something?

    Read the article

  • How to serialize a Bundle?

    - by hermo
    I'd like to serialize a Bundle object, but can't seem to find a simple way of doing it. Using Parcel doesn't seem like an option, since I want to store the serialized data to file. Any ideas on ways to do this? The reason I want this is to save and restore the state of my activity, also when it's killed by the user. I already create a Bundle with the state I want to save in onSaveInstanceState. But android only keeps this Bundle when the activity is killed by the SYSTEM. When the user kills the activity, I need to store it myself. Hence i'd like to serialize and store it to file. Of course, if you have any other way of accomplishing the same thing, i'd be thankful for that too. Edit: I decided to encode my state as a JSONObject instead of a Bundle. The JSON object can then be put in a Bundle as a Serializable, or stored to file. Probably not the most efficient way, but it's simple, and it seems to work ok.

    Read the article

  • Databinding problem in dropdownlist box by generics in C#

    - by sakir-ali
    I want to implement stack in my program by Genericx. I have a textbox and button to add elements in stack, a dropdownlist box and a button to bind total stack in dropdownlist box. I have generic class and the code is below: [Serializable] public class myGenClass<T> { private T[] _elements; private int _pointer; public myGenClass(int size) { _elements = new T[size]; _pointer = 0; } public void Push(T item) { if (_pointer > _elements.Length - 1) { throw new Exception("Stack is full"); } _elements[_pointer] = item; _pointer++; } public T Pop() { _pointer--; if (_pointer < 0) { throw new Exception("Stack is empty"); } return _elements[_pointer]; } public T[] myBind() { T[] showall = new T[_pointer]; Array.Copy(_elements,showall, _pointer); T[] newarray = showall; Array.Reverse(showall); return showall; } } and my .cs page is below: public partial class _Default : System.Web.UI.Page { myGenClass<int> mystack = new myGenClass<int>(25); protected void Button1_Click(object sender, EventArgs e) { mystack.Push(Int32.Parse(TextBox1.Text)); //DropDownList1.Items.Add(mystack.Pop().ToString()); TextBox1.Text = string.Empty; TextBox1.Focus(); } protected void Button2_Click(object sender, EventArgs e) { //string[] db; //db = Array.ConvertAll<int, string>(mystack.myBind(), Convert.ToString); DropDownList1.DataSource = mystack.myBind(); DropDownList1.DataBind(); } } but when I bind the datasource property of dropdownlist box to generic type return array (i.e. myBind()), it shows empty... Please help..

    Read the article

  • Difficulty setting ArrayList to java.sql.Blob to save in DB using hibernate

    - by me_here
    I'm trying to save a java ArrayList in a database (H2) by setting it as a blob, for retrieval later. If this is a bad approach, please say - I haven't been able to find much information on this area. I have a column of type Blob in the database, and Hibernate maps to this with java.sql.Blob. The code I'm struggling with is: Drawings drawing = new Drawings(); try { ByteArrayOutputStream bos = new ByteArrayOutputStream(); ObjectOutputStream oos = null; oos = new ObjectOutputStream(bos); oos.writeObject(plan.drawingPane21.pointList); byte[] buff = bos.toByteArray(); Blob drawingBlob = null; drawingBlob.setBytes(0, buff); drawing.setDrawingObject(drawingBlob); } catch (Exception e){ System.err.println(e); } The object I'm trying to save into a blob (plan.drawingPane21.pointList) is of type ArrayList<DrawingDot>, DrawingDot being a custom class implementing Serializable. My code is failing on the line drawingBlob.setBytes(0, buff); with a NullPointerException. Help appreciated.

    Read the article

  • EJB3 Entity and Lazy Problem

    - by Stefano
    My Entity beAN have 2 list: @Entity @Table(name = "TABLE_INTERNAL") public class Internal implements java.io.Serializable { ...SOME GETTERS AND SETTERS... private List<Match> matchs; private List<Regional> regionals; } mapped one FetchType.LAZY and one FetchType.EAGER : @OneToMany(fetch = FetchType.LAZY,mappedBy = "internal") public List<Match> getMatchs() { return matchs; } public void setMatchs(List<Match> matchs) { this.matchs = matchs; } @ManyToMany(targetEntity = Regional.class, mappedBy = "internals", fetch =FetchType.EAGER) public List<Regional> getRegionals() { return regionals; } public void setRegionals(List<Regional> regionals) { this.regionals = regionals; } I need both lists full ! But I cant put two FetchType.EAGER beacuse it's an error. I try some test: List<Internal> out; out= em.createQuery("from Internal").getResultList(); out= em.createQuery("from Internal i JOIN FETCH i.regionals ").getResultList(); I'm not able to fill both lists...Help!!! Stefano

    Read the article

  • How to test a DAO with JPA implementation ?

    - by smallufo
    Hi I came from the Spring camp , I don't want to use Spring , and am migrating to JavaEE6 , But I have problem testing DAO + JPA , here is my simplified sample : public interface PersonDao { public Person get(long id); } This is a very basic DAO , because I came from Spring , I believe DAO still have it value , so I decided to add a DAO layer . public class PersonDaoImpl implements PersonDao , Serializable { @PersistenceContext(unitName = "test", type = PersistenceContextType.EXTENDED) EntityManager entityManager ; public PersonDaoImpl() { } @Override public Person get(long id) { return entityManager .find(Person.class , id); } } This is a JPA-implemented DAO , I hope the EE container or the test container able to inject the EntityManager. public class PersonDaoImplTest extends TestCase { @Inject protected PersonDao personDao; @Override protected void setUp() throws Exception { //personDao = new PersonDaoImpl(); } public void testGet() { System.out.println("personDao = " + personDao); // NULL ! Person p = personDao.get(1L); System.out.println("p = " + p); } } This is my test file . OK , here comes the problem : Because JUnit doesn't understand @javax.inject.Inject , the PersonDao will not be able to injected , the test will fail. How do I find a test framework that able to inject the EntityManager to the PersonDaoImpl , and @Inject the PersonDaoImpl to the PersonDao of TestCase ? I tried unitils.org , but cannot find a sample like this , it just directly inject the EntityManagerFactory to the TestCast , not what I want ...

    Read the article

  • Duplicate column name by JPA with @ElementCollection and @Inheritance

    - by gerry
    I've created the following scenario: @javax.persistence.Entity @Inheritance(strategy = InheritanceType.TABLE_PER_CLASS) public class MyEntity implements Serializable{ @Id @GeneratedValue protected Long id; ... @ElementCollection @CollectionTable(name="ENTITY_PARAMS") @MapKeyColumn (name = "ENTITY_KEY") @Column(name = "ENTITY_VALUE") protected Map<String, String> parameters; ... } As well as: @javax.persistence.Entity public class Sensor extends MyEntity{ @Id @GeneratedValue protected Long id; ... // so here "protected Map<String, String> parameters;" is inherited !!!! ... } So running this example, no tables are created and i get the following message: WARNUNG: Got SQLException executing statement "CREATE TABLE ENTITY_PARAMS (Entity_ID BIGINT NOT NULL, ENTITY_VALUE VARCHAR(255), ENTITY_KEY VARCHAR(255), Sensor_ID BIGINT NOT NULL, ENTITY_VALUE VARCHAR(255))": com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Duplicate column name 'ENTITY_VALUE' I also tried overriding the attributes on the Sensor class... @AttributeOverrides({ @AttributeOverride(name = "ENTITY_KEY", column = @Column(name = "SENSOR_KEY")), @AttributeOverride(name = "ENTITY_VALUE", column = @Column(name = "SENSOR_VALUE")) }) ... but the same error. Can anybody help me?

    Read the article

  • @OneToMany and composite primary keys?

    - by Kris Pruden
    Hi, I'm using Hibernate with annotations (in spring), and I have an object which has an ordered, many-to-one relationship which a child object which has a composite primary key, one component of which is a foreign key back to the id of the parent object. The structure looks something like this: +=============+ +================+ | ParentObj | | ObjectChild | +-------------+ 1 0..* +----------------+ | id (pk) |-----------------| parentId | | ... | | name | +=============+ | pos | | ... | +================+ I've tried a variety of combinations of annotations, none of which seem to work. This is the closest I've been able to come up with: @Entity public class ParentObject { @Column(nullable=false, updatable=false) private String id; @OneToMany(mappedBy="object", fetch=FetchType.EAGER) @IndexColumn(name = "pos", base=0) private List<ObjectChild> attrs; ... } @Entity public class ChildObject { @Embeddable public static class Pk implements Serializable { @Column(nullable=false, updatable=false) private String objectId; @Column(nullable=false, updatable=false) private String name; @Column(nullable=false, updatable=false) private int pos; ... } @EmbeddedId private Pk pk; @ManyToOne @JoinColumn(name="parentId") private ParentObject parent; ... } I arrived at this after a long bout of experimentation in which most of my other attempts yielded entities which hibernate couldn't even load for various reasons. The error I get when I try to read one of these objects (they seem to save OK), I get an error of this form: org.hibernate.exception.SQLGrammarException: could not initialize a collection: ... And the root cause is this: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown column 'attrs0_.id' in 'field list' I'm sure I'm missing something simple, but the documentation is not clear on this matter, and I haven't been able to find any examples of this anywhere else. Thanks!

    Read the article

  • java serialization problems with different JVMs

    - by Alberto
    I am having trouble using serialization in Java. I've searched the web for a solution but haven't found an answer yet. The problem is this - I have a Java library (I have the code and I export it to an archive prior to executing the code) which I need to use with two differents JVMs. One JVM is on the server (Ubuntu, running Java(TM) JRE SE Runtime Environment (build 1.7.0_09-b05)) and the other on Android 2.3.3. I compiled the library in Java 1.6. Now, I am trying to import to the client, an object exported from the server, but I receive this error: java.io.InvalidClassException: [Lweka.classifiers.functions.MultilayerPerceptron$NeuralEnd;; Incompatible class (SUID): [Lweka.classifiers.functions.MultilayerPerceptron$NeuralEnd;: static final long serialVersionUID =-359311387972759020L; but expected [Lweka.classifiers.functions.MultilayerPerceptron$NeuralEnd;: static final long serialVersionUID =1920571045915494592L; I do have an explicit serial version UID declared on the class MultilayerPerceptron$NeuralEnd, like this: protected class NeuralEnd extends NeuralConnection { private static final long serialVersionUID = 7305185603191183338L; } Where NeuralConnection implements the java.io.Serializable interface. If I do a serialver on MultilayerPerceptron$NeuralEnd I receive the serialVersionUID which I declared. So, why have both JVMs changed this value? Can you help me? Thanks, Alberto

    Read the article

  • JSF:Resourcebundle Problem with Internationalization

    - by Sven
    I implemented internationalization like in that tutorial! When I change the language in my app. It works. But only until the next request happens. Then language settings are reset to my standard language -.- What am I missing here: LanguageBean.java @ManagedBean(name="language") @SessionScoped public class LanguageBean implements Serializable{ private static final long serialVersionUID = 1L; private String localeCode; private static Map<String,Object> countries; static{ countries = new LinkedHashMap<String,Object>(); countries.put("Deutsch", Locale.GERMAN); //label, value countries.put("English", Locale.ENGLISH); } public Map<String, Object> getCountriesInMap() { return countries; } public String getLocaleCode() { return localeCode; } public void setLocaleCode(String localeCode) { this.localeCode = localeCode; } //value change event listener public void countryLocaleCodeChanged(ValueChangeEvent e){ String newLocaleValue = e.getNewValue().toString(); //loop country map to compare the locale code for (Map.Entry<String, Object> entry : countries.entrySet()) { if(entry.getValue().toString().equals(newLocaleValue)){ FacesContext.getCurrentInstance() .getViewRoot().setLocale((Locale)entry.getValue()); } } } } my facelets template: <h:selectOneMenu value="#{language.localeCode}" onchange="submit()" valueChangeListener="#{language.countryLocaleCodeChanged}"> <f:selectItems value="#{language.countriesInMap}" /> </h:selectOneMenu> faces-config: <application> <locale-config> <default-locale>de</default-locale> </locale-config> <resource-bundle> <base-name>org.dhbw.stg.wwi2008c.mopro.ui.text</base-name> <var>msg</var> </resource-bundle> </application>

    Read the article

  • database design to speed up hibernate querying of large dataset

    - by paddydub
    I currently have the below tables representing a bus network mapped in hibernate, accessed from a Spring MVC based bus route planner I'm trying to make my route planner application perform faster, I load all the above tables into Lists to perform the route planner logic. I would appreciate if anyone has any ideas of how to speed my performace Or any suggestions of another method to approach this problem of handling a large set of data Coordinate Connections Table (INT,INT,INT)( Containing 50,000 Coordinate Connections) ID, FROMCOORDID, TOCOORDID 1 1 2 2 1 17 3 1 63 4 1 64 5 1 65 6 1 95 Coordinate Table (INT,DECIMAL, DECIMAL) (Containing 4700 Coordinates) ID , LAT, LNG 0 59.352669 -7.264341 1 59.352669 -7.264341 2 59.350012 -7.260653 3 59.337585 -7.189798 4 59.339221 -7.193582 5 59.341408 -7.205888 Bus Stop Table (INT, INT, INT)(Containing 15000 Stops) StopID RouteID COORDINATEID 1000100001 100 17 1000100002 100 18 1000100003 100 19 1000100004 100 20 1000100005 100 21 1000100006 100 22 1000100007 100 23 This is how long it takes to load all the data from each table: stop.findAll = 148ms, stops.size: 15670 Hibernate: select coordinate0_.COORDINATEID as COORDINA1_2_, coordinate0_.LAT as LAT2_, coordinate0_.LNG as LNG2_ from COORDINATES coordinate0_ coord.findAll = 51ms , coordinates.size: 4704 Hibernate: select coordconne0_.COORDCONNECTIONID as COORDCON1_3_, coordconne0_.DISTANCE as DISTANCE3_, coordconne0_.FROMCOORDID as FROMCOOR3_3_, coordconne0_.TOCOORDID as TOCOORDID3_ from COORDCONNECTIONS coordconne0_ coordinateConnectionDao.findAll = 238ms ; coordConnectioninates.size:48132 Hibernate Annotations @Entity @Table(name = "STOPS") public class Stop implements Serializable { @Id @GeneratedValue @Column(name = "COORDINATEID") private Integer CoordinateID; @Column(name = "LAT") private double latitude; @Column(name = "LNG") private double longitude; } @Table(name = "COORDINATES") public class Coordinate { @Id @GeneratedValue @Column(name = "COORDINATEID") private Integer CoordinateID; @Column(name = "LAT") private double latitude; @Column(name = "LNG") private double longitude; } @Entity @Table(name = "COORDCONNECTIONS") public class CoordConnection { @Id @GeneratedValue @Column(name = "COORDCONNECTIONID") private Integer CoordinateID; /** * From Coordinate_id value */ @Column(name = "FROMCOORDID", nullable = false) private int fromCoordID; /** * To Coordinate_id value */ @Column(name = "TOCOORDID", nullable = false) private int toCoordID; //private Coordinate toCoordID; }

    Read the article

  • @Autowire strange problem

    - by Javi
    Hello, I have a strange behaviour when autowiring I have a similar code like this one, and it works @Controller public class Class1 { @Autowired private Class2 object2; ... } @Service @Transactional public class Class2{ ... } The problem is that I need that the Class2 implements an interface so I've only changed the Class2 so it's now like: @Controller public class Class1 { @Autowired private Class2 object2; ... } @Service @Transactional public class Class2 implements IServiceReference<Class3, Long>{ ... } public interface IServiceReference<T, PK extends Serializable> { public T reference(PK id); } with this code I get a org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type for Class2. It seems that @ Transitional annotation is not compatible with the interface because if I remove the @Transitional annotation or the "implements IServiceReference" the problem disapears and the bean is injected (though I need to have both in this class). It also happens if I put the annotation @Transitional in the methods instead of in the Class. I use Spring 3.0.2 if this helps. Is not compatible the interface with the transactional method? May it be a Spring bug? Thanks

    Read the article

  • Serializing MDI Winforms for persistency

    - by Serge
    Hello, basically my project is an MDI Winform application where a user can customize the interface by adding various controls and changing the layout. I would like to be able to save the state of the application for each user. I have done quite a bit of searching and found these: http://stackoverflow.com/questions/2076259/how-to-auto-save-and-auto-load-all-properties-in-winforms-c http://stackoverflow.com/questions/1669522/c-save-winform-or-controls-to-file Basically from what I understand, the best approach is to serialize the data to XML, however winform controls are not serializable, so I would have use surrogate classes: http://www.codeproject.com/KB/dotnet/Surrogate_Serialization.aspx Now, do I need to write a surrogate class for each of my controls? I would need to write some sort of a recursive algorithm to save all my controls, what is the best approach to do accomplish that? How would I then restore all the windows, should I use the memento design pattern for that? If I want to implement multiple users later, should I use Nhibernate to store all the object data in a database? I am still trying to wrap my head around the problem and if anyone has any experience or advice I would greatly appreciate it, thanks.

    Read the article

  • Elegantly handling constraint violations in EJB/JPA environment?

    - by hallidave
    I'm working with EJB and JPA on a Glassfish v3 app server. I have an Entity class where I'm forcing one of the fields to be unique with a @Column annotation. @Entity public class MyEntity implements Serializable { private String uniqueName; public MyEntity() { } @Column(unique = true, nullable = false) public String getUniqueName() { return uniqueName; } public void setUniqueName(String uniqueName) { this.uniqueName = uniqueName; } } When I try to persist an object with this field set to a non-unique value I get an exception (as expected) when the transaction managed by the EJB container commits. I have two problems I'd like to solve: 1) The exception I get is the unhelpful "javax.ejb.EJBException: Transaction aborted". If I recursively call getCause() enough times, I eventually reach the more useful "java.sql.SQLIntegrityConstraintViolationException", but this exception is part of the EclipseLink implementation and I'm not really comfortable relying on it's existence. Is there a better way to get detailed error information with JPA? 2) The EJB container insists on logging this error even though I catch it and handle it. Is there a better way to handle this error which will stop Glassfish from cluttering up my logs with useless exception information? Thanks.

    Read the article

  • how to atomically claim a row or resource using UPDATE in mysql

    - by Igor
    i have a table of resources (lets say cars) which i want to claim atomically. if there's a limit of one resource per one user, i can do the following trick: UPDATE cars SET user = 'bob' WHERE user IS NULL LIMIT 1 SELECT * FROM cars WHERE user IS bob that way, i claim the resource atomically and then i can see which row i just claimed. this doesn't work when 'bob' can claim multiple cars. i realize i can get a list of cars already claimed by bob, claim another one, and then SELECT again to see what's changed, but that feels hackish. What I'm wondering is, is there some way to see which rows i just updated with my last UPDATE? failing that, is there some other trick to atomically claiming a row? i really want to avoid using SERIALIZABLE isolation level. If I do something like this: 1 SELECT id FROM cars WHERE user IS NULL 2 <here, my PHP or whatever picks a car id> 3 UPDATE cars SET user = 'bob' WHERE id = <the one i picked> would REPEATABLE READ be sufficient here? in other words, could i be guaranteed that some other transactions won't claim the row my software has picked during step 2?

    Read the article

  • Saving twice don't update my object in JDO

    - by Javi
    Hello I have an object persisted in the GAE datastore using JDO. The object looks like this: public class MyObject implements Serializable, StoreCallback { @PrimaryKey @Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY) @Extension(vendorName="datanucleus", key="gae.encoded-pk", value="true") private String id; @Persistent private String firstId; ... } As usually when the object is stored for the first time a new id value is generated for the identifier. I need that if I don't provide a value for firstId it sets the same value as the id. I don't want to solve it with a special getter which checks for null value in firstId and then return the id value because I want to make queries relating on firstId. I can do it in this way by saving the object twice (Probably there's a better way to do this, but I'll do it in this way until I find a better one). But it is not working. when I debug it I can see that result.firstId is set with the id value and it seems to be persisted, but when I go into the datastore I see that firstId is null (as it was saved the first time). This save method is in my DAO and it is called in another save method in the service annotated with @Transactional. Does anyone have any idea why the second object in not persisted properly? @Override public MyObject save(MyObject obj) { PersistenceManager pm = JDOHelper.getPersistenceManagerFactory("transactions-optional"); MyObject result = pm.makePersistent(obj); if(result.getFirstId() == null){ result.setFirstId(result.getId()); result = pm.makePersistent(result); } return result; } Thanks.

    Read the article

  • How do I add a default namespace with no prefix using XMLSerializer

    - by OldBob
    Hi Using C# and .Net 3.5; I am trying to generate an XML document that contains the default namespace without a prefix using XMLSerializer. eg. <?xml version="1.0" encoding="utf-8" ?> <MyRecord ID="9266" xmlns="http://www.website.com/MyRecord"> <List> <SpecificItem> using the following code string xmlizedString = null; MemoryStream memoryStream = new MemoryStream(); XmlSerializer xs = new XmlSerializer(typeof(ExportMyRecord)); XmlSerializerNamespaces xmlnsEmpty = new XmlSerializerNamespaces(); xmlnsEmpty.Add(string.Empty, string.Empty); XmlTextWriter xmlTextWriter = new XmlTextWriter(memoryStream, Encoding.UTF8); xs.Serialize(xmlTextWriter, myRecord, xmlnsEmpty); memoryStream = (MemoryStream)xmlTextWriter.BaseStream; xmlizedString = this.UTF8ByteArrayToString(memoryStream.ToArray()); and class structure [Serializable] [XmlRoot("MyRecord")] public class ExportMyRecord { [XmlAttribute("ID")] public int ID { get; set; } Now, I've tried various options XmlSerializer xs = new XmlSerializer(typeof(ExportMyRecord),"http://www.website.com/MyRecord"); or [XmlRoot(Namespace = "http://www.website.com/MyRecord", ElementName="MyRecord")] gives me <?xml version="1.0" encoding="utf-8"?> <q1:MylRecord ID="9266" xmlns:q1="http://www.website.com/MyRecord"> <q1:List> <q1:SpecificItem> I need the XML to have the namespace without the prefix as it's going to a third party provider and they reject all other alternatives. Any suggestions? No responses so far. Has anyone experienced this or know how to solve it?

    Read the article

  • SerializationException with custom GenericIdentiy?

    - by MunkiPhD
    I'm trying to implement my own GenericIdentity implementation but keep receiving the following error when it attempts to load the views (I'm using asp.net MVC): System.Runtime.Serialization.SerializationException was unhandled by user code Message="Type is not resolved for member 'OpenIDExtendedIdentity,Training.Web, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'." Source="WebDev.WebHost" I've ended up with the following class: [Serializable] public class OpenIDExtendedIdentity : GenericIdentity { private string _nickName; private int _userId; public OpenIDExtendedIdentity(String name, string nickName, int userId) : base(name, "OpenID") { _nickName = nickName; _userId = userId; } public string NickName { get { return _nickName; } } public int UserID { get { return _userId; } } } In my Global.asax I read a cookie's serialized value into a memory stream and then use that to create my OpenIDExtendedIdentity object. I ended up with this attempt at a solution after countless tries of various sorts. It works correctly up until the point where it attempts to render the views. What I'm essentially attempting to achieve is the ability to do the following (While using the default Role manager from asp.net): User.Identity.UserID User.Identity.NickName ... etc. I've listed some of the sources I've read in my attempt to get this resolved. Some people have reported a Cassini error, but it seems like others have had success implementing this type of custom functionality - thus a boggling of my mind. http://forums.asp.net/p/32497/161775.aspx http://ondotnet.com/pub/a/dotnet/2004/02/02/effectiveformsauth.html http://social.msdn.microsoft.com/Forums/en-US/netfxremoting/thread/e6767ae2-dfbf-445b-9139-93735f1a0f72

    Read the article

  • Mapping Hashmap of Coordinates in Hibernate with Annotation

    - by paddydub
    I've just started using hibernate and I'm trying to map walking distance between two coordinates into a hashmap, There can be many connections from one "FromCoordinate" to another "ToCoordinate". I'm not sure if i've implemented this correctly, What annotations do i need to map this MashMap? Thanks HashMap coordWalkingConnections = new HashMap(); @Entity @Table(name = "COORDCONNECTIONS") public class CoordinateConnection implements Serializable{ private static final long serialVersionUID = -1624745319005591573L; /** auto increasing id number */ @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "ID") @id private int id; @Embedded public FromCoordinate fromCoord; @Embedded public ToCoordinate toCoord; HashMap<FromCoordinate, ArrayList<ToCoordinate >> coordWalkingConnections = new HashMap<FromCoordinate, ArrayList<ToCoordinate >>(); } public class FromCoordinate implements ICoordinate { @Column(name = "FROM_LAT") private double latitude; @Column(name = "FROM_LNG") private double longitude; } public class ToCoordinate implements ICoordinate { @Column(name = "TO_LAT") private double latitude; @Column(name = "TO_LNG") private double longitude; @Column(name = "DISTANCE") private double distance; } DATABASE STRUCTURE id FROM_LAT FROM_LNG TO_LAT TO_LNG Dist 1 43.352669 -6.264341 43.350012 -6.260653 0.38 2 43.352669 -6.264341 43.352669 -6.264341 0.00 3 46.352669 -6.264341 43.353373 -6.262013 0.17 4 47.352465 -6.265865 43.351290 -6.261200 0.25 5 45.452578 -6.265768 43.352788 -6.264396 0.01 6 45.452578 -6.265768 45.782788 -6.234523 0.01 ..... ... . Example HashMap for HashMap<Coordinate, ArrayList<Coordinate>> <KEY{43.352669 -6.264341}, Arraylist VALUES{(43.350012,-6.260653,0.383657), (43.352669, -6.264341, 0.000095), (43.353373, -6.262013, 0.173201)}> <KEY{47.352465 -6.265865}, Arraylist VALUES{(43.351290,-6.261200,0.258781)}> <KEY{45.452578 -6.265768}, Arraylist VALUES{(43.352788,-6.264396,0.013726),(45.782788,-6.234523,0.017726)}>

    Read the article

  • Hibernate Mapping Annotation Question?

    - by paddydub
    I've just started using hibernate and I'm trying to map walking distance between two coordinates into a hashmap, There can be many connections from one "FromCoordinate" to another "ToCoordinate". I'm not sure if i've implemented this correctly, What annotations do i need to map this MashMap? Thanks @Entity @Table(name = "COORDCONNECTIONS") public class CoordinateConnection implements Serializable{ private static final long serialVersionUID = -1624745319005591573L; /** auto increasing id number */ @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "ID") @id private int id; @Embedded public FromCoordinate fromCoord; @Embedded public ToCoordinate toCoord; HashMap<Coordinate, ArrayList<Coordinate>> coordWalkingConnections = new HashMap<Coordinate, ArrayList<Coordinate>>(); } public class FromCoordinate implements ICoordinate { @Column(name = "FROM_LAT") private double latitude; @Column(name = "FROM_LNG") private double longitude; } public class ToCoordinate implements ICoordinate { @Column(name = "TO_LAT") private double latitude; @Column(name = "TO_LNG") private double longitude; @Column(name = "DISTANCE") private double distance; } DATABASE STRUCTURE id FROM_LAT FROM_LNG TO_LAT TO_LNG Dist 1 43.352669 -6.264341 43.350012 -6.260653 0.38 2 43.352669 -6.264341 43.352669 -6.264341 0.00 3 46.352669 -6.264341 43.353373 -6.262013 0.17 4 47.352465 -6.265865 43.351290 -6.261200 0.25 5 45.452578 -6.265768 43.352788 -6.264396 0.01 6 45.452578 -6.265768 45.782788 -6.234523 0.01 ..... ... . Example HashMap for HashMap<Coordinate, ArrayList<Coordinate>> <KEY{43.352669 -6.264341}, Arraylist VALUES{(43.350012,-6.260653,0.383657), (43.352669, -6.264341, 0.000095), (43.353373, -6.262013, 0.173201)}> <KEY{47.352465 -6.265865}, Arraylist VALUES{(43.351290,-6.261200,0.258781)}> <KEY{45.452578 -6.265768}, Arraylist VALUES{(43.352788,-6.264396,0.013726),(45.782788,-6.234523,0.017726)}>

    Read the article

  • Interfaces with structs, by reference using Generics

    - by Fraga
    I can't pass by reference an interface with a struct in it, what am I doing wrong? Here is the example code: class Processor<T> where T : new() { public Processor() { Data = new T(); } public T Data; } class PeriodsProcessor : Processor<Periods> { public PeriodsProcessor() { DataBase DB = new DataBase(); Console.WriteLine(Data.Value); DB.ModifyData<Period>(Data); Console.WriteLine(Data.Value); Console.ReadLine(); } } public class Period { public string Name; } public interface IDataTable<T> { string Value { get; set; } T Filter { get; set; } } [Serializable] public struct Periods : IDataTable<Period> { public string Value { get; set; } public Period Filter { get; set; } } public class DataBase { public void ModifyData<T>(IDataTable<T> data) where T : new() { data.Value = "CHANGE"; } } class Program { static void Main(string[] args) { PeriodsProcessor PeriodsProcessor = new PeriodsProcessor(); } }

    Read the article

  • How to deserialize an element as an XmlNode?

    - by mackenir
    When using Xml serialization in C#, I want to deserialize a part of my input XML to an XmlNode. So, given this XML: <Thing Name="George"> <Document> <subnode1/> <subnode2/> </Document> </Thing> I want to deserialize the Document element to an XmlNode. Below is my attempt which given the XML above, sets Document to the 'subnode1' element rather than the 'Document' element. How would I get the code to set the Document property to the Document element? using System; using System.IO; using System.Xml; using System.Xml.Serialization; [Serializable] public class Thing { [XmlAttribute] public string Name {get;set;} public XmlNode Document { get; set; } } class Program { static void Main() { const string xml = @" <Thing Name=""George""> <Document> <subnode1/> <subnode2/> </Document> </Thing>"; var s = new XmlSerializer(typeof(Thing)); var thing = s.Deserialize(new StringReader(xml)) as Thing; } } However, when I use an XmlSerializer to deserialize the XML above to an instance of Thing, the Document property contains the child element 'subnode1', rather than the 'doc' element. How can I get the XmlSerializer to set Document to an XmlNode containing the 'doc' element.

    Read the article

  • C# - Class Type as Parameter in methods

    - by Claudio
    Hi guys, I'm using SQLite.cs wrapper for helping me with the database and I have this method for create XML from a table, that is working fine. public void GenerateInvoiceXML(string filePath) { var invoices = app.db.Table<Invoice>().ToList(); XmlSerializer serializer = new XmlSerializer( typeof(List<Invoice>) ); TextWriter writer = new StreamWriter(filePath); serializer.Serialize(writer,invoices); writer.Close(); } All tables that I have are defined like this: [Serializable] public class Invoice { [PrimaryKey, AutoIncrement] public int Id { get; set; } public string Supplier {get; set;} public string Date {get; set;} public string PaymentMethod {get; set;} public string Notes {get; set;} public Invoice(int newID) { Id = newID; } public Invoice() { } } But I want to change this method for something like this: public void GenerateInvoiceXML(string filePath, Type table) { var dataForXML = app.db.Table<table>().ToList(); XmlSerializer serializer = new XmlSerializer( typeof(List<table>) ); TextWriter writer = new StreamWriter(filePath); serializer.Serialize(writer,dataForXML); writer.Close(); } Does anybody have an idea how to do it? Kind Regards, Claudio

    Read the article

< Previous Page | 14 15 16 17 18 19 20 21 22 23 24 25  | Next Page >