I need to mock with Mockito :
ResultSet rs = oracle.getConnection().getMetaData().getIndexInfo(null, null, table.getName(), true, true);
final ResultSetMetaData data = rs.getMetaData();
First, I've got an advice for you. Do not mock it. Really. There is a golden rule of mocks - mock what you own. So, no mocks for Connection, MetaData, ResultSet etc. You will get into troubles if you follow this path.
However, if you still want to do it, RETURNS_DEEP_STUB is what you are looking for:
http://docs.mockito.googlecode.com/hg/org/mockito/Mockito.html#RETURNS_DEEP_STUBS
Related
I know the title is not really explaining the problem so I will try to give more details.
I have a String in the Controller, something like this (keep in mind that this String is not manually written since it's dynamic, there are 7 filters and I want to return the information based on the filters selected, so I can't just put the String in the #Query value, since some filters will remain untouched and you cannot SELECT * WHERE value = *)
String query = "SELECT * FROM table WHERE column1=value1 AND column2=value2"
Now, the Queries are made in the Repository, but I really have no idea how to make the value of that query to be this String, something like this :
#Query(value = query, nativeQuery = true)
public List<ExampleEntity> testFunction(String query);
My first idea was to do this :
#Query(value = "?", nativeQuery = true)
public List<ExampleEntity> testFunction(String query);
But it inputs the whole String inside ' '
'SELECT * FROM table WHERE column1=value1 AND column2=value2'
(now that I think about this, it does that because the compiler sees this as like I'm trying to set the value of something to be the String, makes sense but I wish there could be a way to simply set the input of the function to be the value of the Query :/ )
Sooo ... is there any other way to use that string as the query value?
Annotations are on classes, they are set at compile time. You can’t change them at runtime. Spring can’t change them either.
What you could do is check out how to use Specifications to construct queries, or use your existing query constructing code within a custom JPA repository. Defining repositories with interfaces is a good option for simple cases, but this is not a simple case.
It would be better to move your query building code out of the controller layer and into the repository, btw. Even assuming everything in the current workflow is secure, having a repository take a native query as a parameter just isn’t a good look, it’s wide open to abuse.
I took a different approach to solve this problem that is much simpler than using Specifications.
After searching how can you send a Query in the Controller I found jdbcTemplate that is Standard in Spring (no need to add a dependency or anything else)
These are the steps that I took and in the end, everything works at it should.
1 Autowire the JdbcTemplate in the Controller
#Autowired
private JdbcTemplate jdbcTemplate;
2 Set the return to be the Query
return jdbcTemplate.queryForList(query);
Keep in mind that this is for multiple Columns, if you have to return only one column I think you have to use something like this :
return jdbcTemplate.query(query, new SingleColumnMapper(Example.class)
It might not be the safest or the most recommended way of solving this, but it worked for me.
We have a ASP.NET MVC 3 C# project running NHibernate 3 and Castle.ActiveRecord for MySQL, and we trying to get "one session per request" to work with this tutorial.
And it seems to work for some stuff, but when we do SaveAndFlush(), the command gives us an error:
A different object with the same identifier value
was already associated with the session: 142
And if we try to do only Save() we got the same message so it has nothing to do with the Flush() function.
I have find some result when I search but nothing I can use to get it to work.
Something I have not tested because I don't know how I do, is,
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id")
Any ideas?
Basically the problem might lie in that you are trying to Save() an object that already exists. If the object has an identifier already set (object.Id = 142) then the object does not need to be saved.
If you make changes to it, and need to save those changes you need to use the Update() method (as mentioned by #OskarBerggren) or the SaveOrUpdate() which basically checks and decides whether to save the object or update it. The last one might work best in your case. Change your current,
session.Save(object);
to,
session.SaveOrUpdate(object);
The Session object is from NHibernate's SessionFactory implementation. However, I see you are using ActiveRecordMediator, so you can use,
ActiveRecordMediator.GetSessionFactoryHolder().CreateSession()
to create a Session you can use to save your models.
I'm developing Web Service that has access to database via JDBC. I'm using DAO pattern. I've implemented all necessary methods: findAll, add, update, delete. But I got confused with update method. It has Object as input parameter. But how does he know which field needs to be updated. For example, I need to update field 'name' I use query 'update table set name='smth where id=2' but if I need to update 'surname'?? what is the best practice to tell update method what actually to update?
thank you
You'll need to change your method signature to include a Map of column names and values.
public interface FooDao<K, V> {
// other methods here, of course.
public void update(V target, Map<String, Object> parameters);
}
Have a look at the Spring JDBC template for a nice example of how to design and implement such a thing.
Can anyone post here an example of how to use the MySQLJDBCDataModel in Apache Mahout including the instantiating of a DataSource ?
I want to use the DataModel to generate Recommendations. A Databasetable (lets call it ratings) with user_id, task_id and rating already exists i just need to know how to access this information without creating my own implementation of DataModel.
Thanks in advance!
If you don't want to use JNDI:
MysqlDataSource dataSource = new MysqlDataSource();
dataSource.setServerName("my_database_host");
dataSource.setUser("my_user");
dataSource.setPassword("my_password");
dataSource.setDatabaseName("my_database_name");
JDBCDataModel dataModel = new MySQLJDBCDataModel(
dataSource, "my_prefs_table", "my_user_column",
"my_item_column", "my_pref_value_column", "my_timestamp_column");
Have a look in MySQLJDBCDataModel for details...
The class has a constructor that takes the name of the DataSource, or the DataSource. You just pass it the name (and optionally override the names of the table, columns, etc.) -- what else do you need here?
If you want to know how to look something up in JNDI, then it's as follows, but again this is done for you:
Context context = new InitialContext();
DataSource dataSource =
(DataSource) context.lookup("java:comp/env/" + dataSourceName);
context.close();
(You probably want to use ReloadFromJDBCDataModel too here.)
I'm working my way through the MVC Storefront code and trying to follow the path of a repository, a service and a model that is a poco, outside of the dbml/data context. It's pretty easy to follow actually, until I started writing tests and things failed in a way I just don't understand.
In my case, the primary key is a uniqueidentifier instead of an int field. The repository returns an IQueryable:
public IQueryable<Restaurant> All()
{
return from r in _context.Restaurants select new Restaurant(r.Id)
{
Name = r.Name
};
}
In this case, Restaurant is a Models.Restaurant of course, and not _context.Restaurants.Restaurant.
Filtering in the service class (or in repository unit tests) against All(), this works just as expected:
var results = Repository.All().Where(r => r.Name == "BW<3").ToList();
This works just fine, has one Model.Restaurant. Now, if I try the same things with the pkid:
var results = Repository.All().Where(r => r.Id == new Guid("088ec7f4-63e8-4e3a-902f-fc6240df0a4b")).ToList();
If fails with:
The member 'BurningPlate.Models.Restaurant.Id' has no supported translation to SQL.
If seen some similiar posts where people say it's because r => r.Id is [Model.Restaurants] is a class level the linq2sql layer isn't aware of. To me, that means the the first version shouldn't work either. Of course, if my pk is an int, it works just fine.
What's really going on here? Lord knows, it's not very intuitive to have one work and one not work. What am I misunderstanding?
I think the problem here is due to using a constructor overload, and expecting the query to fill it in. When you do a projection like this, you have to put all the things you want to be in the projection query in the actual projection itself. Otherwise Linq won't include that in the SQL query.
So, rewrite your bits like so:
return from r in _context.Restaurants select new Restaurant()
{
Id=r.Id,
Name = r.Name
};
This should fix it up.
Not having actually typed this code out, have you tried
var results = Repository.All().Where(r => r.Id.Equals(new Guid("088ec7f4-63e8-4e3a-902f-fc6240df0a4b")).ToList()
Ninja
this probably has to do with fact that you trying to instantiate the guid in the query, and I think that LINQ to SQL is trying to convert that to actual SQL code before the object is created.
Try instantiating before the query and not on the query.