BigInteger in Pascal - biginteger

Is there BigInteger type exists in Free Pascal?
In Java and C# exists the type BigInteger and BigDecimal.
How can I write the same code I have written in Java below in Pascal:
package bigint;
import java.math.BigInteger;
/**
* #author Istvan
*/
public class bigint {
public static void main(String[] args) {
BigInteger a = new BigInteger("12345678913546876542545054683656469434");
BigInteger b = new BigInteger("983435472457463464685743648468650354684046846841");
BigInteger c = a.multiply(b);
System.out.println("c="+c);
}
}

You will find a few different solutions in this Lazarus forum thread and here.

Related

how to store PostgreSQL jsonb using SpringBoot + JPA?

I'm working on a migration software that will consume unknown data from REST services.
I already think about use MongoDB but I decide to not use it and use PostgreSQL.
After read this I'm trying to implement it in my SpringBoot app using Spring JPA but I don't know to map jsonb in my entity.
Tried this but understood nothing!
Here is where I am:
#Repository
#Transactional
public interface DnitRepository extends JpaRepository<Dnit, Long> {
#Query(value = "insert into dnit(id,data) VALUES (:id,:data)", nativeQuery = true)
void insertdata( #Param("id")Integer id,#Param("data") String data );
}
and ...
#RestController
public class TestController {
#Autowired
DnitRepository dnitRepository;
#RequestMapping(value = "/dnit", method = RequestMethod.GET)
public String testBig() {
dnitRepository.insertdata(2, someJsonDataAsString );
}
}
and the table:
CREATE TABLE public.dnit
(
id integer NOT NULL,
data jsonb,
CONSTRAINT dnit_pkey PRIMARY KEY (id)
)
How can I do this?
Note: I don't want/need an Entity to work on. My JSON will always be String but I need jsonb to query the DB
Tried this but understood nothing!
To fully work with jsonb in Spring Data JPA (Hibernate) project with Vlad Mihalcea's hibernate-types lib you should just do the following:
1) Add this lib to your project:
<dependency>
<groupId>com.vladmihalcea</groupId>
<artifactId>hibernate-types-52</artifactId>
<version>2.2.2</version>
</dependency>
2) Then use its types in your entities, for example:
#Data
#NoArgsConstructor
#Entity
#Table(name = "parents")
#TypeDef(name = "jsonb", typeClass = JsonBinaryType.class)
public class Parent implements Serializable {
#Id
#GeneratedValue(strategy = SEQUENCE)
private Integer id;
#Column(length = 32, nullable = false)
private String name;
#Type(type = "jsonb")
#Column(columnDefinition = "jsonb")
private List<Child> children;
#Type(type = "jsonb")
#Column(columnDefinition = "jsonb")
private Bio bio;
public Parent(String name, List children, Bio bio) {
this.name = name;
this.children = children;
this.bio = bio;
}
}
#Data
#NoArgsConstructor
#AllArgsConstructor
public class Child implements Serializable {
private String name;
}
#Data
#NoArgsConstructor
#AllArgsConstructor
public class Bio implements Serializable {
private String text;
}
Then you will be able to use, for example, a simple JpaRepository to work with your objects:
public interface ParentRepo extends JpaRepository<Parent, Integer> {
}
parentRepo.save(new Parent(
"parent1",
asList(new Child("child1"), new Child("child2")),
new Bio("bio1")
)
);
Parent result = parentRepo.findById(1);
List<Child> children = result.getChildren();
Bio bio = result.getBio();
You are making things overly complex by adding Spring Data JPA just to execute a simple insert statement. You aren't using any of the JPA features. Instead do the following
Replace spring-boot-starter-data-jpa with spring-boot-starter-jdbc
Remove your DnitRepository interface
Inject JdbcTemplate where you where injecting DnitRepository
Replace dnitRepository.insertdata(2, someJsonDataAsString ); with jdbcTemplate.executeUpdate("insert into dnit(id, data) VALUES (?,to_json(?))", id, data);
You were already using plain SQL (in a very convoluted way), if you need plain SQL (and don't have need for JPA) then just use SQL.
Ofcourse instead of directly injecting the JdbcTemplate into your controller you probably want to hide that logic/complexity in a repository or service.
There are already several answers and I am pretty sure they work for several cases. I don't wanted to use any more dependencies I don't know, so I look for another solution.
The important parts are the AttributeConverter it maps the jsonb from the db to your object and the other way around. So you have to annotate the property of the jsonb column in your entity with #Convert and link your AttributeConverter and add #Column(columnDefinition = "jsonb") as well, so JPA knows what type this is in the DB. This should already make it possible to start the spring boot application. But you will have issues, whenever you try to save() with the JpaRepository. I received the message:
PSQLException: ERROR: column "myColumn" is of type jsonb but
expression is of type character varying.
Hint: You will need to rewrite or cast the expression.
This happens because postgres takes the types a little to serious.
You can fix this by a change in your conifg:
datasource.hikari.data-source-properties: stringtype=unspecified
datasource.tomcat.connection-properties: stringtype=unspecified
Afterwards it worked for me like a charm, and here is a minimal example.
I use JpaRepositories:
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
#Repository
public interface MyEntityRepository extends JpaRepository<MyEntity, Integer> {
}
The Entity:
import javax.persistence.Column;
import javax.persistence.Convert;
public class MyEntity {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
protected Integer id;
#Convert(converter = MyConverter.class)
#Column(columnDefinition = "jsonb")
private MyJsonObject jsonContent;
}
The model for the json:
public class MyJsonObject {
protected String name;
protected int age;
}
The converter, I use Gson here, but you can map it however you like:
import javax.persistence.AttributeConverter;
import javax.persistence.Converter;
#Converter(autoApply = true)
public class MyConverter implements AttributeConverter<MyJsonObject, String> {
private final static Gson GSON = new Gson();
#Override
public String convertToDatabaseColumn(MyJsonObject mjo) {
return GSON.toJson(mjo);
}
#Override
public MyJsonObject convertToEntityAttribute(String dbData) {
return GSON.fromJson(dbData, MyJsonObject.class);
}
}
SQL:
create table my_entity
(
id serial primary key,
json_content jsonb
);
And my application.yml (application.properties)
datasource:
hikari:
data-source-properties: stringtype=unspecified
tomcat:
connection-properties: stringtype=unspecified
For this case, I use the above tailored converter class, you are free to add it in your library. It is working with the EclipseLink JPA Provider.
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.log4j.Logger;
import org.postgresql.util.PGobject;
import javax.persistence.AttributeConverter;
import javax.persistence.Converter;
import java.io.IOException;
import java.sql.SQLException;
import java.util.Map;
#Converter
public final class PgJsonbToMapConverter implements AttributeConverter<Map<String, ? extends Object>, PGobject> {
private static final Logger LOGGER = Logger.getLogger(PgJsonbToMapConverter.class);
private static final ObjectMapper MAPPER = new ObjectMapper();
#Override
public PGobject convertToDatabaseColumn(Map<String, ? extends Object> map) {
PGobject po = new PGobject();
po.setType("jsonb");
try {
po.setValue(map == null ? null : MAPPER.writeValueAsString(map));
} catch (SQLException | JsonProcessingException ex) {
LOGGER.error("Cannot convert JsonObject to PGobject.");
throw new IllegalStateException(ex);
}
return po;
}
#Override
public Map<String, ? extends Object> convertToEntityAttribute(PGobject dbData) {
if (dbData == null || dbData.getValue() == null) {
return null;
}
try {
return MAPPER.readValue(dbData.getValue(), new TypeReference<Map<String, Object>>() {
});
} catch (IOException ex) {
LOGGER.error("Cannot convert JsonObject to PGobject.");
return null;
}
}
}
Usage example, for an entity named Customer.
#Entity
#Table(schema = "web", name = "customer")
public class Customer implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
#Convert(converter = PgJsonbToMapConverter.class)
private Map<String, String> info;
public Customer() {
this.id = null;
this.info = null;
}
// Getters and setter omitted.
If you're using R2DBC you can use dependency io.r2dbc:r2dbc-postgresql, and use type io.r2dbc.postgresql.codec.Json in your member attributes of an entity class, e.g.:
public class Rule {
#Id
private String client_id;
private String username;
private String password;
private Json publish_acl;
private Json subscribe_acl;
}

Can not query for non basic attributes JPA

I have a DBTweet class which knows it's comments as list of other DBTweet-objects (#OneToMany) and which knows it's parent tweet (#ManyToOne) if it is a comment. Parent is set to null if the tweet is no comment.
#Entity
#XmlRootElement
public class DBTweet extends DBIdentified {
#Basic
Date publishedOn;
#Basic
String username;
#Basic
String text;
#Basic
boolean isAnswer;
#OneToMany(mappedBy = "parent")
List<DBTweet> answers = new ArrayList<>();
#ManyToOne
DBTweet parent = null;
}
When i want to query for all tweets, that are no comments i want to use this query
#GET
#Path("/tweet/newestfirst")
#Produces(MediaType.APPLICATION_JSON)
public Response readNewestTweet() {
final CriteriaBuilder builder = this.entityManager.getCriteriaBuilder();
final CriteriaQuery<DBTweet> query = builder.createQuery(DBTweet.class);
final Root<DBTweet> from = query.from(DBTweet.class);
final Predicate predicate = builder.isNull(from.get(DBTweet_.parent));
final Order order = builder.desc(from.get(DBTweet_.publishedOn));
query.select(from).where(predicate).orderBy(order);
return Response.ok(this.entityManager.createQuery(query).getResultList()).build();
}
But the non-basic properties of DBTweet are not known by the compiler.
It just says:
cannot find symbol
symbol: variable parent
location: class de.ls5.wt2.DBTweet_
In the compiled file there are only the basic properties.
#StaticMetamodel(DBTweet.class)
public abstract class DBTweet_ extends DBIdentified_ {
public static volatile SingularAttribute<DBTweet, Date> publishedOn;
public static volatile SingularAttribute<DBTweet, String> text;
public static volatile SingularAttribute<DBTweet, String> username;
public static volatile SingularAttribute<DBTweet, Boolean> isAnswer;
public DBTweet_() {
}
}
Why can't i find the answers or parent property in the compiled file?
How can i solve this?
Any ideas?

SonarQube (Sonar) + EclipseLink: incorrect error 'Comparison of String parameter using == or !='

I have the following class, using EclipseLink JPA:
package my.package;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.SequenceGenerator;
import javax.persistence.Version;
import my.package.api.Address;
#Entity(name = "Address")
#SequenceGenerator(name = "sequence", sequenceName = "seq_address")
public class AddressJpaEntity implements Address {
#Id
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "sequence")
private Long id;
#Version
private Long version;
private String street;
public AddressJpaEntity() {
}
public AddressJpaEntity(String street) {
this.street = street;
}
#Override
public Long getId() {
return id;
}
public Long getVersion() {
return version;
}
public void setVersion(Long version) {
this.version = version;
}
#Override
public String getStreet() {
return street;
}
#Override
public void setStreet(String street) {
this.street = street;
}
}
When I do a SonarQube-run, I get a lot of the following (incorrect) errors:
Bad practice - Comparison of String parameter using == or !=
This code compares a java.lang.String parameter for reference equality using the == or != operators. Requiring callers to pass only String constants or interned strings to a method is unnecessarily fragile, and rarely leads to measurable performance gains. Consider using the equals(Object) method instead.
findbugs | ES_COMPARING_PARAMETER_STRING_WITH_EQ
Comparison of String parameter using == or != in my.package.AddressJpaEntity._persistence_set(String, Object)
For now, I solved it by setting the issues as false positive, but we will add more similar classes in the future and I don't want to do this each time.
How can I make Sonar not mark these errors, without using 'False positive' all the time?
Please check this post for a solution. It shows how to create an exclusion filter for FindBugs.
In this case, you'll want to ignore ES_COMPARING_PARAMETER_STRING_WITH_EQ warnings.
I still think it's incorrect to use ==, though, but apparently, that's not something you can help.

get max value of column using jpa criteria query

I want to get the maximum value of column relationId from table ElementRelationType
I have written code but its giving error
CriteriaBuilder cb1 = entityManager.getCriteriaBuilder();
CriteriaQuery<ElementRelationTypes> cq1 = cb1.createQuery(ElementRelationTypes.class);
Root<ElementRelationTypes> root = cq1.from(ElementRelationTypes.class);
cq1.select(cb1.max(root.get("relationId")));
select and max both giving error
how to get the integer max value
public class ElementRelationTypes {
private RelationId relationLangPK=new RelationId();
private Country country;
private Status status;
#EmbeddedId
public RelationId getRelationLangPK() {
return relationLangPK;
}
public void setRelationLangPK(RelationId relationLangPK) {
this.relationLangPK = relationLangPK;
}
#Transient
public Integer getRelationId() {
return getRelationLangPK().getRelationId();
}
public void setRelationId(Integer relationId) {
getRelationLangPK().setRelationId(relationId);
}
#Transient
public Language getLanguage() {
return getRelationLangPK().getLanguage();
}
public void setLanguageCode(Language language) {
getRelationLangPK().setLanguage(language);
}
and
public class RelationId implements Serializable {
private static final long serialVersionUID = 1L;
private Integer relationId;
private Language language;
#JoinColumn(name=PersistenseConstants.ELEMENT_RELATION_TYPE_COL_RELATION_ID)
public Integer getRelationId() {
return relationId;
}
public void setRelationId(Integer relationId) {
this.relationId = relationId;
}
#OneToOne
#JoinColumn(name=PersistenseConstants.LANGUAGE_ENTITY_COL_LANG_CODE)
public Language getLanguage() {
return language;
}
public void setLanguage(Language language) {
this.language = language;
}
You didn't post which errors do you receive, so I have to guess.
CriteriaBuilder.max accepts Expression<N> where N extends Number
At the same time Root.get by default returns Path<Object> which is inconvertible to Expression<Number>.
So to make your call to max work you need to specify generic parameter to root.get:
cq1.select(cb1.max(root.<Number>get("relationId")));
here you can replace Number with an actual type of relationId (Long, BigInteger etc.)
UPDATE: #perissf addressed another issue with your code. If you are going to select maximal value (which is numeric) you should declare your CriteriaQuery as a query to Number not ElementRelationTypes

How to make a request factory non-transportable type transportable?

According to this answer: Is com.vividsolutions.jts.geom.Geometry directly transportable using requestfactory? Geometry is ( a particular case of a type that is ) non- transportable using requestfactory.
So then would this work? :
#Entity
public class Poi {
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Id
private Integer id;
#Type(type="org.hibernate.spatial.GeometryType")
private Geometry geom;
//bi-directional many-to-one association to PoiCateg
#ManyToOne
#JoinColumn(name="id_cat")
private PoiCateg poiCateg;
#Version
private Integer version;
public Poi() {
}
public Integer getId() {
return this.id;
}
public void setId(Integer id) {
this.id = id;
}
public Geometry getGeom() {
return this.geom;
}
public void setGeom(Geometry geom) {
this.geom = geom;
}
public PoiCateg getPoiCateg() {
return this.poiCateg;
}
public void setPoiCateg(PoiCateg poiCateg) {
this.poiCateg = poiCateg;
}
//not your standard getters and setters
public String getGeomClient() {
return //result of method that converts from Geometry object to WKT string representation
}
public void setGeomClient(String geom) {
this.geom = // result of method that converts from String to Geometry
}
}
and then my modified entity proxy for Poi would look like:
#ProxyFor(value=Poi.class)
public interface PoiProxy implements EntityProxy {
public Integer getId() ;
public void setId(Integer id);
public PoiCategEntityProxy getPoiCateg() ;
public void setPoiCateg(PoiCateg poiCateg);
//not your standard getters and setters
public String getGeomClient() ;
public void setGeomClient(String geom) ;
}
since getGeomClient and setGeomClient in the server entity contain a geometry type will it be a problem on the client?
EDIT1: forgot about #Version private Integer version; mistake fixed.
Not only it'll work but that's the (simplest) way to make it work.
Alternatives involve using wrappers/builders. I've also seen people using EntityProxys where the stringified value is used as the identifier, but beware that RequestFactory requires a per-request cache.