In following code I am trying to find out department table data according to nDeptId. If that object is null I am throwing DataRetrievalFailureException. How to handle this exception in another spring project using RestTemplate
Department deptmentObj = new Department();
deptmentObj = depRepo.findByNDeptId(accountObj.nDeptId);
if (deptmentObj == null) {
throw new DataRetrievalFailureException("DataRetrievalFailureException for ndeptid");
}
}
can any one tell me what I need to change?
Related
I'm kinda stuck on this topic.
This is what i already found out.
A good tutorial was :
Using MySQL in Spring Boot via Spring Data JPA and Hibernate
http://blog.netgloo.com/2014/10/27/using-mysql-in-spring-boot-via-spring-data-jpa-and-hibernate/
I also found some information how to make single page application with hsqldb.
But i really want to create something that permanent saves the users data to the database using mysql.
But in order to use angular http i need json. Can i convert the urls like
/create?email=[email]&name=[name]
To json how should i proceed. Does anyone knows good tutorials on this. Or are there better way's to proceed.
The simplest/handy way to consuming JSON with Spring Boot is using a Java class that resembles your JSON (https://stackoverflow.com/a/6019761).
So, you can follow the tutorial you linked, then use a controller like this one to handle JSONs:
#RestController
public class UserController {
#RequestMapping(
value = "/user/create",
method = RequestMethod.POST,
consumes = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<?> createUser(#RequestBody User user) {
try {
// Handle the User object here
userDao.save(user);
}
catch (Exception ex) {
return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
}
return new ResponseEntity<>(HttpStatus.OK);
}
// ...
}
Receiving a JSON like this (at the url /user/create):
{email: "john#doe.com", name: "John Doe"}
An user will be saved in your database.
Responding with JSON
Moreover, if you want to send a response as JSON from your controller you should create a java object then send it back as response, within the ResponseEntity object.
For example, suppose to have this class:
public class SuccessDto {
private String success;
public SuccessDto(String success) {
this.success = success;
}
}
You can change your controller in this way:
public ResponseEntity<SuccessDto> createUser(#RequestBody User user) {
// ...
return new ResponseEntity<>(
new SuccessDto("true"),
HttpStatus.OK
);
}
and you will have this JSON as response
{success: "true"}
if you have already managed to use it with HSQLDB, it's juste a matter of database properties (like the JDBC URL) and schema initialization.
Can you provide the code sample of the controller, how you save the data (via a Repository or a simple DAO ?) and the application.properties
Hi I am trying to write small app with REST Json. I have some method that returns ArrayList of entity objects. And I am doing that:
#RequestMapping(value="/workers/", method = RequestMethod.GET)
public #ResponseBody ArrayList<Workers> showAllEmployes() throws Exception
{
ArrayList<Workers> workers = new ArrayList<Workers>();
workers = (ArrayList<Workers>) spiroService.getAllWorkers();
return workers;
}
And after this I got:
HTTP Status 500. The server encountered an internal error that prevented it from fulfilling this request.
When I try to return primitive data type then all is ok. I have nothing in server logs. And I have necessary imports. Please some tip.
Seems you have issue in produce json format, try this.
#RequestMapping(value = "/workers/", method = RequestMethod.GET,
produces={MediaType.APPLICATION_JSON_VALUE})
I've been using Rick Strahl's DataContextFactory code (Linq to SQL DataContext Lifetime Management) in a data layer consumed by an ASP.Net application. It works great because the current datacontext is stored in the HttpContext.Items collection. I know that I'm reusing the same datacontext per web request.
However, I've been unable to use the factory successfully in an WCF service. On a non HttpContext app, the factory stores the datacontext in a thread data slot.
Thread.AllocateNamedDataSlot(key)
The problem is, no matter how I set up the ConcurrencyMode and InstanceContextMode in my service, the threads are reused each call and the same dataContext is reused. I don't want this. I only want a single datacontext to exist per service method call. Is there any way this can be achieved using a factory? I'm unable to find any unique information on each client call to use as an identifier for my datacontext so it won't be reused by other requests...regardless if it is the same client.
I want to consume my business layer and not access my data layer directly, but I'm afraid I might have to dictate my own units of work and datacontexts in my WCF service. Has anybody had any luck using some sort of factory for their datacontexts in a WCF service? I was hoping there was a way for my factory to know if it was being consumed by a WCF service and then handle the storing of the datacontext uniquely
public static T GetScopedDataContext<T>()
{
if (HttpContext.Current != null)
return (T)GetWebRequestScopedDataContextInternal(typeof(T), typeof(T).ToString(), null);
// What can I put here to handle WCF services differently?
return (T)GetThreadScopedDataContextInternal(typeof(T), typeof(T).ToString(), null);
}
And then what could be done here to achieve what I want?
static object GetThreadScopedDataContextInternal(Type type, string key, string ConnectionString)
{
if (key == null)
key = "__WRSCDC_" + Thread.CurrentContext.ContextID.ToString();
LocalDataStoreSlot threadData = Thread.GetNamedDataSlot(key);
object context = null;
if (threadData != null)
context = Thread.GetData(threadData);
if (context == null)
{
if (ConnectionString == null)
context = Activator.CreateInstance(type);
else
context = Activator.CreateInstance(type, ConnectionString);
if (context != null)
{
if (threadData == null)
threadData = Thread.AllocateNamedDataSlot(key);
Thread.SetData(threadData, context);
}
}
return context;
}
I got the same problem.
I use Castle.Windsor IOC container + "PerWebRequest" lifestyle, and it works in a similar way as your factory under the hood.
I'm still trying to find the perfect solution for my needs, but I have an intermediate solution that can help you : making your WCF service run with a HttpContext :
1) In your WCF project, ask for ASP.Net compatibility
<system.serviceModel>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true"/>
</system.serviceModel>
2) Add an attribute to your service to manage this compatibility
[AspNetCompatibilityRequirements(
RequirementsMode = AspNetCompatibilityRequirementsMode.Required)]
public class MyService : IMyContract
{
...
}
Source : Code rant
Why this keep bugging me all day.
I have an entity with several references where i get from a context which I then Dispose.
Do some Changes and try to SubmitChanges(). While calling SubmitChanges() without .Attach() seems to simply do nothing. When using .Attach() I get the Exception :
An attempt has been made to Attach or Add an entity that is not new, perhaps having been loaded from another DataContext. This is not supported.
Any ideas?
L2S is very picky about updating an entity that came from a different DB context. In fact, you cannot do it unless you 'detach' it first from the context it came from. There are a couple different ways of detaching an entity. One of them is shown below. This code would be in your entity class.
public virtual void Detach()
{
PropertyChanging = null;
PropertyChanged = null;
}
In addition to this, you can also serialize your entity using WCF based serialization. Something like this:
object ICloneable.Clone()
{
var serializer = new DataContractSerializer(GetType());
using (var ms = new System.IO.MemoryStream())
{
serializer.WriteObject(ms, this);
ms.Position = 0;
return serializer.ReadObject(ms);
}
}
I am using LINQ2SQL and I have a table called Customers with three columns
CustmerID, CustomerCode, CustomerName
CustmerID is Primery Key(and Identity=yes) and CustomerCode is just UniqueKey.
When I am updating this table using LINQ to SQL with duplicate customercode, I expect to see DuplicateKeyException but it is going into the general exception block instead of DuplicateKeyException block. Any ideas?
This is the code
public void Update(Customer cust)
{
using (LINQDemoDataContext db = new LINQDemoDataContext())
{
Customers entity = CustomerMapper.ToEntity(new Customers(), cust);
try
{
db.Customers.Attach(entity, true);
db.SubmitChanges();
}
//Concurrency Exception
catch (ChangeConflictException)
{
throw new ChangeConflictException("A concurrency error occurred!");
}
//duplicate record
catch (DuplicateKeyException)
{
throw new DuplicateKeyException(entity.CustmerCode);
}
//everything else
catch (Exception ex)
{
throw ex;
}
}
}
I am using VisualWebDeveloperExpress 2008 and SQL Express 2005.
Thanks & Regards,
Supremestar
If memory serves, and I may be wrong here, the DuplicateKeyException only fires for the primary key of the table.
I ran into this same problem, where the duplicate key objects were being retained in-memory even though they were not getting inserted into the database. I came up with the following work around:
MyDataContext _myDataContext = new MyDataContext(ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString);
public void AddObject(object myObject)
{
try
{
_myDataContext.Objects.InsertOnSubmit(myObject);
_myDataContext.SubmitChanges();
}
catch (System.Data.Linq.DuplicateKeyException ex)
{
_myDataContext = new MyDataContext(ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString);
throw ex;
You can then catch and handle (or ignore) the thrown DuplicateKeyException in the caller.
Another work around (albeit inefficient and memory hogging) is to create a new data context inside the AddObject method instead of using the shared data context instantiated as a class member.
I had the problem when adding an entity i got from a different DataContext.
(I bound the FooDb-Property of a BarDb-Entity to the SelectedValue from a DropDownList, which had a Table from a short-living DataContext as DataSource)
Let's look at the Linq2Sql internal Attach(entity):
private void attach_FooDb(FooDb entity){
this.SendPropertyChanging();
entity.BarDb = this;
}
And the BarDb Property set:
set{
BarDb previousValue = this._BarDb.Entity;
if (((previousValue != value) || (this._BarDb.HasLoadedOrAssignedValue == false))){
this.SendPropertyChanging();
if ((previousValue != null)){
this._BarDb.Entity = null;
previousValue.FooDb.Remove(this);
}
this._BarDb.Entity = value;
if ((value != null)){
value.FooDb.Add(this);
this._FK_Bar = value.ID;
}else{
this._FK_Bar = default(System.Guid);
}
this.SendPropertyChanged("BarDb");
}
}
So when attaching to a FooDb, the corresponding DataContext will recognize the BarDb Entity as newly created and added, even though it already existed in the Database.
You can solve it by:
only using a single DataContext or
creating a BarDb_safe Property in the submitting DataContext, which will first request the "equal" entity from the database, applies all properties and then attaches it the usual way.